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
Under Chart Tools, on the Design tab, in the Data group, click Select Data. In the Select Data Source dialog box, in the Legend Entries (Series) box, click the data series that you want to change the order of. Click the Move Up or Move Down arrows to move the data series to the position that you want.
How can I reorder the stacks in a stacked bar plot? Change the order of the levels of the factor variable you're creating the stacks with in the aes thetic mapping .
Reordering in ggplot is done using theme() function. Within this, we use axis. text. x with the appropriate value to re-order accordingly.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With