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



Question:

From the online bar chart guide:

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

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

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


Solution:1

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


Solution:2

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


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

enter image description here


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »