I've been using ggplot2 to create a simple grouped boxplot by:
ggplot(data=all_data, aes(x=Season,y=`Depth (m)`,fill=site))
geom_boxplot()
xlab(NULL)
Which makes this
But there are several things I'd like to edit. First is the order of the boxes, I'd like to keep 'dry' on the left and 'wet' on the right but I want to reverse the site order so that 'Upstream' is on the left and 'downstream' is on the right within each group. Also, I tried to add error bar width and shapes on the mean values but when I use something like:
ggplot(data=all_data, aes(x=Season,y=`Depth (m)`,fill=site))
geom_boxplot()
stat_boxplot(geom = 'errorbar',width=0.1)
stat_summary(fun=mean, geom="point",shape=88,size=3)
xlab(NULL)
It produces this
I'd appreciate any help editing this.
CodePudding user response:
To rearrange the Upstream / Downstream categories, convert site
to a factor with the appropriate levels. To have your errorbars and points line up with your boxplots, you need to ensure that you include position = position_dodge(width = 0.75)
to their layers, otherwise they will fall between the boxplots.
So your code would look something like this:
ggplot(data=all_data, aes(x = Season, y = `Depth (m)`,
fill = factor(site, c('Upstream', 'Downstream'))))
geom_boxplot()
stat_boxplot(geom = 'errorbar', width = 0.1,
position = position_dodge(width = 0.75))
stat_summary(fun = mean, geom = "point", shape = 88, size = 3,
position = position_dodge(width = 0.75))
labs(x = NULL, fill = 'Site')
Data Used
There was no data supplied by the OP, so I have made a data set with similar characteristics using this code:
set.seed(1)
all_data <- data.frame(Season = rep(c('Dry', 'Wet'), each = 200),
`Depth (m)` = c(rnorm(100, 1.5, 0.5),
rnorm(100, 1.75, 0.25),
rnorm(100, 1.6, 0.3),
rnorm(100, 1.9, 0.5)),
site = rep(rep(c('Downstream', 'Upstream'), 2), each = 100),
check.names = FALSE)
Running the OP's plot code on this data produces:
ggplot(data = all_data, aes(x=Season,y=`Depth (m)`,fill=site))
geom_boxplot()
xlab(NULL)