在ggplot boxplot中的填充组中显示单独的均值 [英] Displaying separate means within fill groups in ggplot boxplot

查看:204
本文介绍了在ggplot boxplot中的填充组中显示单独的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分组的箱线图,使用3类数据。将一个类别设置为箱形图的x轴,将另一个类别设置为填充,将最后一个类别设置为构面类别。我想显示每个填充组的均值,但是使用 stat_summary 只给我x轴类别的均值,而没有分开填充的均值:





这是当前代码:

  demoplot <-ggplot(demo,aes(x = variable,y = value))
demoplot + geom_boxplot(aes(fill = category2),位置= position_dodge(.9))+
stat_summary(fun.y =平均值,colour = black,geom = point,shape = 18,size = 4,)+
facet_wrap(〜category1 )

有什么方法可以显示每个类别的均值2,而无需手动计算和绘制点?调整位置闪避实际上并没有帮助,因为它只是一个计算得出的平均值。在 mean()函数中创建条件是否明智?




I have a grouped boxplot using data with 3 categories. One category is set as the x-axis of the boxplots, the other is set as the fill, and the last one, as a faceting category. I want to display the means for each fill group, but using stat_summary only gives me the mean for the x-axis category, without separating the means for the fill:

Here is the current code:

demoplot<-ggplot(demo,aes(x=variable,y=value))
demoplot+geom_boxplot(aes(fill=category2),position=position_dodge(.9))+
stat_summary(fun.y=mean, colour="black", geom="point", shape=18, size=4,) +
facet_wrap(~category1)

Is there any way to display the mean for each category2 without having to manually compute and plot the points? Adjusting the position dodge doesn't really help, as it's just one computed mean. Would creating conditions within the mean() function be advisable?

For anyone interested, here's the data:

Advanced thanks for any enlightenment on this.

解决方案

Ggplot needs to have explicit information on grouping here. You can do that either by using a aes(group=....) in the desired layer, or moving the fill=... to the main call to ggplot. Without explicit grouping for a layer, ggplot will group by the factor on the x-axis. Here's some sample code with fake data:

library(ggplot2)
set.seed(123)

nobs <- 1000
dat <- data.frame(var1=sample(LETTERS[1:3],nobs, T),
                  var2=sample(LETTERS[1:2],nobs,T),
                  var3=sample(LETTERS[1:3],nobs,T),
                  y=rnorm(nobs))

p1 <- ggplot(dat, aes(x=var1, y=y)) +
  geom_boxplot(aes(fill=var2), position=position_dodge(.9)) +
  facet_wrap(~var3) +
  stat_summary(fun.y=mean, geom="point", aes(group=var2), position=position_dodge(.9), 
               color="black", size=4)

这篇关于在ggplot boxplot中的填充组中显示单独的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆