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

As you can see, the order of colors is not respected.
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