Boxplot with mean and standard deviation in ggPlot2 (plus Jitter)
[This article was first published on Statistic on aiR, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
When you create a boxplot in R, it automatically computes median, first and third quartile (“hinges“) and 95% confidence interval of median (“notches“).Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
But we would like to change the default values of boxplot graphics with the mean, the mean + standard deviation, the mean – S.D., the min and the max values.
Here is an example solved using ggplot2 package. Plus here are represented points (the single values) jittered horizontally.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggplot2) | |
# create fictitious data | |
a <- runif(10) | |
b <- runif(12) | |
c <- runif(7) | |
d <- runif(15) | |
# data groups | |
group <- factor(rep(1:4, c(10, 12, 7, 15))) | |
# dataframe | |
mydata <- data.frame(c(a,b,c,d), group) | |
names(mydata) <- c("value", "group") | |
# function for computing mean, DS, max and min values | |
min.mean.sd.max <- function(x) { | |
r <- c(min(x), mean(x) - sd(x), mean(x), mean(x) + sd(x), max(x)) | |
names(r) <- c("ymin", "lower", "middle", "upper", "ymax") | |
r | |
} | |
# ggplot code | |
p1 <- ggplot(aes(y = value, x = factor(group)), data = mydata) | |
p1 <- p1 + stat_summary(fun.data = min.mean.sd.max, geom = "boxplot") + geom_jitter(position=position_jitter(width=.2), size=3) + ggtitle("Boxplot con media, 95%CI, valore min. e max.") + xlab("Gruppi") + ylab("Valori") |
To leave a comment for the author, please follow the link and comment on their blog: Statistic on aiR.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.