开发者

How do I change the stacking order in a bar chart in ggplot2?

开发者 https://www.devze.com 2022-12-22 20:43 出处:网络
开发者_如何学PythonFrom the online bar chart guide: qplot(factor(cyl), data=mtcars, geom=\"bar\", fill=factor(gear))
开发者_如何学Python

From the online bar chart guide:

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

How do I change the stacking order in a bar chart in ggplot2?

How do I get 5 to sit on the bottom, 4 above that, and 3 on top?


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


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


To generalize @xiechao's solution (@hadley's doesn't work in latest ggplot), you can reverse the factor orders to achieve this:

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()

How do I change the stacking order in a bar chart in ggplot2?

0

精彩评论

暂无评论...
验证码 换一张
取 消