Change the order of stacked fill columns in ggplot2

15,025

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:

enter image description here

Share:
15,025
vinchinzu
Author by

vinchinzu

Mild Dabbler

Updated on June 09, 2022

Comments

  • vinchinzu
    vinchinzu almost 2 years

    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
    

    enter image description here