我试图将两个时间序列绘制为条形图,一个在另一个之上(未堆叠) . 我正在使用 position="identity"
来实现这一目标,但条形图的输出顺序错误:
library(reshape2)
library(ggplot2)
test<-abs(rnorm(12)*1000)
test<-rbind(test, test+500)
colnames(test)<-month.abb[seq(1:12)]
rownames(test)<-c("first", "second")
otherTest<-apply(test, 2, mean)
test<-melt(test)
#otherTest<-as.data.frame(otherTest)
otherTest <- data.frame(
Var2 = names(otherTest),
value = otherTest
)
otherTest$Var2 = factor(otherTest$Var2, levels = levels(test$Var2))
ggplot(test, aes(x = Var2, y = value, group = 1,order=-as.numeric(Var2))) +
geom_bar(aes(fill = Var1), stat="identity", position="identity") +
geom_line(data = otherTest)
生成下面的图表 . 如您所见,'second'中的值高于'first',因此蓝色条隐藏了粉红色条 . 如何在'second'之上获得'first'?我一直试图重新排序与 Var2
test
相关的因素无济于事 .
2 回答
我不得不重写代码来简化 .
问题出在
position
参数上 . 只需在plot命令中使用position = "stack"
即可创建情节:
Changes in ggplot2 version 2.0.0+
请注意the order aesthetic is officially deprecated . 如果你需要控制因子变量的顺序,我建议使用Hadley的
forcats
包 .有new geom_col() which is short-hand for geom_bar(stat = "identity") .
有了这个,代码可以简化: