简体   繁体   English

ggplot2 : 用 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")

在此处输入图片说明

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.谢谢你的帮助。

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")

在此处输入图片说明

ggplot2 likes 1 data point for 1 plot point. ggplot2喜欢 1 个数据点为 1 个绘图点。 Create a new data frame with your summary statistics, then plot with stat="identity"使用汇总统计数据创建一个新数据框,然后使用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")

在此处输入图片说明

Try using ggpubr .尝试使用ggpubr It creates ggplot2-like charts.它创建类似 ggplot2 的图表。

library(ggpubr)

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

在此处输入图片说明

Alternatively, add a facet:或者,添加一个方面:

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM