Reputation: 13
I am trying to add a mean to the boxplot, but the mean plots on the side, I cannot figure out how put the mean within the center of the boxplot itself. Please find an example code below.boxplot result Apologies if it has been previously asked, but I could not find anything on the topic.
library(datasets)
library(ggplot2)
airquality$Month <- factor(airquality$Month, labels= c("May", "Jun", "Jul", "Aug", "Sep"))
airquality_trimmed <- airquality[which(airquality$Month == "Jul" | airquality$Month == "Aug" |
airquality$Month == "Sep"), ]
airquality_trimmed$Temp.f <- factor(ifelse(airquality_trimmed$Temp > mean(airquality_trimmed$Temp), 1, 0),
labels = c("Low temp", "High temp"))
BP <- ggplot(airquality_trimmed, aes(x= Month, y= Ozone, fill= Temp.f))+
geom_boxplot(alpha= 0.7)+
scale_y_continuous(name= "Mean ozone in\nparts per billion") +
scale_x_discrete(name= "Month")+
stat_summary(fun= "mean", geom= "point", colour= "black")+
theme_bw()+
scale_fill_brewer(palette = "Accent") +
labs(fill = "Temperature")
BP
Upvotes: 1
Views: 772
Reputation: 12719
Add position = position_dodge(width = 0.75)
to the stat_summary
call:
ggplot(airquality_trimmed, aes(x= Month, y= Ozone, fill= Temp.f))+
geom_boxplot(alpha= 0.7)+
scale_y_continuous(name= "Mean ozone in\nparts per billion") +
scale_x_discrete(name= "Month")+
stat_summary(fun= "mean", geom= "point", colour= "black", position = position_dodge(width = 0.75))+
theme_bw()+
scale_fill_brewer(palette = "Accent") +
labs(fill = "Temperature")
Created on 2020-07-08 by the reprex package (v0.3.0)
Upvotes: 3