I am generating a number of boxplots, each for a different marker, filled by a categorical variable: 'CR' and 'No CR'.
I want the left box in the plot to be the 'No CR'-fill and the right one 'CR'. Like this one:
However, for some plots, I get it the other way around (left 'CR' and right 'No CR')
How can I control (order?) which filling category is left and which one is right?
Here is part of my code:
head(df)
# ID y CR
# 1 1 0 No CR
# 2 2 0 No CR
# 3 3 0 CR
# 4 4 4 No CR
ggplot(df, aes(x = CR, y = y))
geom_boxplot(aes(fill=CR))
labs(title="Highly differential peptides")
scale_fill_manual(values=c("#35978f","#D6604D"))
stat_compare_means( label.y = maxadn,size=5)
CodePudding user response:
You can relevel your CR variable :
df$CR=factor(df$CR,levels=c("No CR","CR"))
and then try to replot
CodePudding user response:
It's nice to include a minimal, reproducible example to make it easier to answer your question thoroughly. First I'll simulate some data:
library("ggplot2")
df <- data.frame(
CR = sample(c("CR", "No CR"), 20, replace=TRUE),
y = rpois(20, 2)
)
Then, as explained in this question, you can either set the limits directly:
ggplot(df, aes(x = CR, y = y))
geom_boxplot(aes(fill=CR))
scale_fill_manual(values=c("#35978f","#D6604D"))
scale_x_discrete(limits=c("No CR", "CR"))
or use factor levels to control the order:
ggplot(df, aes(x = factor(CR, levels=c("No CR", "CR")), y = y))
geom_boxplot(aes(fill=CR))
scale_fill_manual(values=c("#35978f","#D6604D"))
labs(x = "CR")
Without any reordering:
ggplot(df, aes(x = CR, y = y))
geom_boxplot(aes(fill=CR))
scale_fill_manual(values=c("#35978f","#D6604D"))