Reputation: 614
I want to change the order of a stacked bar chart.
For example, in mpg
I want to order the to c("4", "r", "f")
Is the only approach to change the level of the factors?
library(ggplot2)
library(dplyr)
s <- ggplot(mpg, aes(fl, fill=drv)) + geom_bar(position="stack")
s
Upvotes: 11
Views: 23672
Reputation: 15419
The structure of the input data is character:
str(mpg$drv)
> chr [1:234] "f" "f" "f" "f" "f" "f" "f" "4" "4" "4" "4" "4" "4" "4" "4" "4" "4" "4" "r" "r" "r" "r" "r" "r" "r" "r" "r" "r" "4" "4" "4" "4" "f" "f" "f" "f" "f" "f" "f" "f" "f" "f" "f" ...
ggplot will automatically convert character strings to a factor. You can see the default ordering as follows, and this conversion ranks them alphabetically:
levels(as.factor(mpg$drv))
> "4" "f" "r"
To reorder the barplot without changing the original data, you can just refactor the variable within plot itself:
ggplot(mpg, aes(fl, fill = factor(drv, levels=c("4", "r", "f")))) +
geom_bar(position="stack") +
labs(fill = "Drive")
Comparing the results:
Upvotes: 25