ggplot2 : Plot mean with geom_bar

ggplot2 : Plot mean with geom_bar



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.


stat="mean"



Thanks for any help.






This tutorial provides a good description of how to achieve this: r-bloggers.com/using-r-barplot-with-ggplot2

– seaotternerd
May 12 '15 at 6:29






possible duplicate of Plotting the average values for each level in ggplot2

– seaotternerd
May 12 '15 at 6:32




3 Answers
3



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


stat = "summary"


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






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 '15 at 7:00




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


ggplot2


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



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



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)