How to change from a continuous to discrete scale in ggplot (boxplots)?

Hey there,

I am supernew to R and I am trying to find out how to change the colours of my boxplots. My dataset consists of four years: 1977, 1992, 2020 and 2021. When I use color=year in the ggplot function, a continuous scale is used, which means that 2020 and 2021 have almost identical colours as they are so close together.

Is there a way to manually set the colours per year so that they have different colours? I have tried a lot of different things, but it seems that the continuous vs discrete issue keeps coming up.

My code:

ggplot(.,aes(x = as.character(year), y = value, color = year)) +
xlab("") +
ylab("") +
theme_ipsum() +
ggtitle("Groundwater pH, eastern Curacao") +
theme(plot.title = element_text(hjust = 0.5, size=14))+
theme(legend.position = "none") +
geom_jitter(color="grey", size=0.4, alpha=0.9) +
coord_cartesian(ylim = c(5.5, 9)) +
geom_boxplot()+
stat_summary(fun.y=mean, geom="point", shape=23, size=2)

Thank you kindly!!

you can try to convert it to categorical data on the fly by using "colour = as.factor(year)".
In this case you can also define all the colours manually.

1 Like

This works! Great, thank you

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.