如何在ggplot条形图中订购子组?

时间:2013-05-13 17:48:34

标签: r ggplot2

我想在使用geom_bar创建的ggplot的图例和图中订购组。

这是一个例子

mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), 
                     mysubgroup = c("north", "west", "south", "east", "north", "west", "south", "east"), 
                     value = c(5,10,6,12, 4, 4, 3, 5))

我的出发点:

myplot <- ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) + 
            geom_bar(position = "dodge", width = 0.5, stat = "identity")
myplot

enter image description here

我想按照“北”,“南”,“东”,“西”的顺序绘制图例和条形图。

我尝试将scale_fill_discrete(limits = c("north", "south", "east", "west"))添加到情节中。它将图例按所需顺序排列,但不是条形图(尽管条形图已重新排列)。

myplot + scale_fill_discrete(limits = c("north", "south", "east", "west"))

即使我重新排序数据,我也会得到与上面相同的结果:

mydata2 <- mydata[c(1,3,4,2,5,7,8,6),]
myplot2 <- ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) + 
               geom_bar(position = "dodge", width = 0.5, stat = "identity") 
myplot2 + scale_fill_discrete(limits = c("north", "south", "east", "west"))

enter image description here

1 个答案:

答案 0 :(得分:4)

我在写这个问题时想出了答案(并将作为CW发布以邀请贡献)......

答案是让子组成为具有所需顺序级别的“因子”:

mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), 
                     mysubgroup = factor(c("north", "west", "south", "east", 
                                           "north", "west", "south", "east"), 
                                          levels = c("north", "south", "east", "west")), 
                     value = c(5,10,6,12, 4, 4, 3, 5))

ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) + 
            geom_bar(position = "dodge", width = 0.5, stat = "identity")