R ggplot2:重新排列条形图

时间:2017-02-20 01:49:24

标签: r ggplot2

我试图将两个时间序列绘制为条形图,一个在另一个之上(未堆叠)。我正在使用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)

生成下图。如您所见,“秒”中的值高于“第一个”,因此蓝色条隐藏了粉红色条。如何在'秒'之上获得'第一'?我一直试图重新排序与Var2 test相关的因素无效。

enter image description here

2 个答案:

答案 0 :(得分:1)

我不得不重写代码以简化。

library(dplyr)
test1 <- data_frame(month = factor(month.abb, levels=month.abb),
                    value = abs(rnorm(12)*1000), name="first")
glimpse(test1)
#Observations: 12
#Variables: 3
#$ month <fctr> Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
#$ value <dbl> 1477.63915, 690.10964, 218.79066, 338.01241, 1952.10102, 354.65286, 340.09479, 1070....
#$ name  <chr> "first", "first", "first", "first", "first", "first", "first", "first", "first", "fi...

test2 <- data_frame(month = factor(month.abb, levels=month.abb),
                    name="second")
test2$value <- test1$value+500
glimpse(test2)
#Observations: 12
#Variables: 3
#$ month <fctr> Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
#$ name  <chr> "second", "second", "second", "second", "second", "second", "second", "second", "sec...
#$ value <dbl> 1977.6391, 1190.1096, 718.7907, 838.0124, 2452.1010, 854.6529, 840.0948, 1570.0937, ...

test <- data_frame(month = factor(month.abb, levels=month.abb))
test$value <- (test1$value+test2$value)/2
glimpse(test)
#Observations: 12
#Variables: 2
#$ month <fctr> Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
#$ value <dbl> 1727.6391, 940.1096, 468.7907, 588.0124, 2202.1010, 604.6529, 590.0948, 1320.0937, 3...

# Plot
library(ggplot2)
p <- ggplot(NULL, aes(month, value)) + 
    geom_bar(aes(fill = "second"), data = test2, stat="identity") +
    geom_bar(aes(fill = "first"), data = test1, stat="identity") +
    geom_line(data = test, aes(as.numeric(month), value))
p

ggplot2

答案 1 :(得分:1)

问题在于position参数。只需在绘图命令

中使用position = "stack"即可
ggplot(test, aes(x = Var2, y = value, group = 1, order = -as.numeric(Var2))) +
  geom_bar(aes(fill = Var1), stat = "identity", position = "stack") +
  geom_line(data = otherTest)

创建情节:

enter image description here

ggplot2版本2.0.0 +

中的更改

有了这个,代码可以简化:

ggplot(test, aes(x = Var2, y = value, group = 1)) +
  geom_col(aes(fill = Var1), position="stack") +
  geom_line(data = otherTest)