4

我想在用 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

在此处输入图像描述

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

我已经尝试添加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"))

在此处输入图像描述

4

1 回答 1

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")
于 2013-05-13T17:48:51.217 回答