如何更改ggplot2中条形图中的堆叠顺序?

时间:2010-03-11 18:47:41

标签: r ggplot2

来自online bar chart guide

qplot(factor(cyl), data=mtcars, geom="bar", fill=factor(gear)) 

barplot using <code>qplot</code> feature of <code>ggplot2</code>

如何让5个位于底部,4个位于底部,3个位于顶部?

3 个答案:

答案 0 :(得分:5)

qplot(factor(cyl), data=mtcars, geom='bar', fill=factor(gear, level=5:3))

答案 1 :(得分:5)

qplot(factor(cyl), data=mtcars, geom="bar", fill=factor(gear), order = -gear)

答案 2 :(得分:1)

为了概括@ xiechao的解决方案(@ hadley在最新的ggplot中没有工作),你可以反转因子订单来实现这个目标:

library(ggplot2)
data(mtcars)
mtcars$gear <- factor(mtcars$gear)  # First make factor with default levels
mtcars$gear <- factor(mtcars$gear, levels=rev(levels(mtcars$gear)))
qplot(cyl, data=mtcars, geom="bar", fill=gear)
# Or with ggplot
ggplot(mtcars, aes(factor(cyl), fill=gear)) + geom_bar()

enter image description here