41

I have the following data frame:

test2 <- data.frame(groups = c(rep("group1",4), rep("group2",4)), 
    X2 = c(rnorm(4), rnorm(4)) , 
    label = c(rep(1,2),rep(2,2),rep(1,2),rep(2,2)))

and I am plotting the bar graphs for each label per group using:

ggplot(test2, aes(label, X2, fill=as.factor(groups))) + 
    geom_bar(position="dodge", stat="identity")

enter image description here

However, I am cannot seem to be able to find a stat="mean" so I can plot the means on each bar graph instead of the identity.

Thanks for any help.

2

3 Answers 3

100

simply use stat = "summary" and fun.y = "mean"

ggplot(test2) + 
  geom_bar(aes(label, X2, fill = as.factor(groups)), 
           position = "dodge", stat = "summary", fun.y = "mean")

enter image description here

4
  • Wow this is awesome and really elegant. Thanks! Do you happen to know how to get darker colors in a nice way?
    – Cauchy
    May 12, 2015 at 7:00
  • How do you modify this, to add labels on top of the bars?
    – Carrol
    Mar 30, 2020 at 6:31
  • 21
    Tried this with ggplot 3.3.2 and it seems like fun.y has been deprecated. Use fun = "mean" instead.
    – nniloc
    Jun 23, 2020 at 17:52
  • 1
    Is this solution also compatible with geom_errorbar?
    – Rivered
    Jun 29, 2022 at 11:37
6

ggplot2 likes 1 data point for 1 plot point. Create a new data frame with your summary statistics, then plot with stat="identity"

require(reshape2)
plot.data <- melt(tapply(test2$X2, test2$groups,mean), varnames="group", value.name="mean")

 ggplot(plot.data, aes(x=group,y=mean)) + geom_bar(position="dodge", stat="identity")

enter image description here

1

Try using ggpubr. It creates ggplot2-like charts.

library(ggpubr)

ggbarplot(test2, x = "label", y = "X2",
          add = "mean", fill = "groups")

enter image description here

Alternatively, add a facet:

ggbarplot(test2, x = "label", y = "X2",
          add = "mean", fill = "groups",
          facet.by = "groups")

enter image description here

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.