Mohammad
Mohammad

Reputation: 1098

How to print mean, median and sd on boxplots in ggplot?

I have the following boxplot and I'm trying to print the mean, median and sd values on each box, how does that work? Is there a simple way or a simple parameter in geom_boxplot to make this happen? Thanks

ggplot(mpg,aes(x=class,y=cty))+geom_boxplot()

enter image description here

Upvotes: 2

Views: 5765

Answers (1)

Phil
Phil

Reputation: 8107

You'll first need to calculate the summary statistics:

library(dplyr)

summ <- mpg %>% 
  group_by(class) %>% 
  summarize(mean = mean(cty), median = median(cty), sd = sd(cty))

Then use that data frame in your geom_label call.

ggplot(mpg, aes(x = class, y = cty)) + geom_boxplot() + 
  geom_label(data = summ, aes(x = class, y = mean, 
    label = paste("Mean: ", round(mean, 1), "\nMedian: ", median, "\nSD: ", round(sd, 1))))

enter image description here

Not a good looking chart, but you just need to play around with the size and colours to pretty it up, or maybe use geom_text instead of geom_label.

Upvotes: 3

Related Questions