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