Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order of colors is not respected in ggplot's `geom_bar`

I think this is similar to my previous question here but I wasn’t sure how to use the answer there to fix this problem if they are related.

I use this code to create a bar plot.

x <- 1:10
z1 <- c("m", "m", "m", "m", "m", "m", "m", "n", "n", "n")
z2 <- c("m", "m", "m", "m", "p", "p", "p", "n", "n", "n")
z3 <- c("m", "m", "m", "m", "p", "n", "n", "n", "n", "n")
df <- data.frame(x, z1, z2, z3)

colors <- c("m" = "#f8766d", "n" = "#00BA38", "p" = "#619CFF")

df_long <- pivot_longer(df, cols = c("z1", "z2", "z3"), names_to = "variable", values_to = "value")
ggplot(df_long, aes(x = variable, fill = value)) +
  geom_bar() +
  scale_fill_manual(values = colors) +
  xlab("") + ylab("Count") 

The output I get is
enter image description here
As you can see, the order of colors is not respected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think the first bar from bottom to top should be red-green and the second and third bars should be red-blue-green.

Could someone please help me how to fix this?

>Solution :

You could change the levels of your factor variable and use reverse the stacked bars using position_stack(reverse=TRUE) like this:

library(tidyr)
library(ggplot2)
df_long <- pivot_longer(df, cols = c("z1", "z2", "z3"), names_to = "variable", values_to = "value")
df_long$value <- factor(df_long$value, levels = c("m", "p", "n"))
ggplot(df_long, aes(x = variable, fill = value)) +
  geom_bar(position = position_stack(reverse = TRUE)) +
  scale_fill_manual(values = rev(colors)) +
  xlab("") + ylab("Count") 

Created on 2023-02-14 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading