简体   繁体   English

在ggplot boxplot中的填充组中显示单独的平均值

[英]Displaying separate means within fill groups in ggplot boxplot

I have a grouped boxplot using data with 3 categories. 我有一个使用3类数据的分组箱图。 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. 一个类别设置为箱图的x轴,另一个设置为填充,最后一个设置为分面类别。 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: 我想显示每个填充组的均值,但是使用stat_summary只能给出x轴类别的均值,而不分离填充的均值:

刻面的箱形图

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? 有没有办法显示每个类别2的均值,而无需手动计算和绘制点数? Adjusting the position dodge doesn't really help, as it's just one computed mean. 调整位置闪避并没有多大帮助,因为它只是一个计算平均值。 Would creating conditions within the mean() function be advisable? 是否建议在mean()函数内创建条件?

For anyone interested, here's the data: 对于任何感兴趣的人,这里是数据:

Advanced thanks for any enlightenment on this. 感谢对此的任何启示。

Ggplot needs to have explicit information on grouping here. Ggplot需要有关于分组的明确信息。 You can do that either by using a aes(group=....) in the desired layer, or moving the fill=... to the main call to ggplot. 您可以通过在所需图层中使用aes(group=....)或将fill=...移动到主要调用ggplot来实现。 Without explicit grouping for a layer, ggplot will group by the factor on the x-axis. 如果没有对图层进行显式分组,ggplot将按x轴上的因子分组。 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)

在此输入图像描述

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

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