按组统计的stat_summary问题

时间:2018-09-11 15:11:39

标签: r ggplot2

我在这里的最终目标是让stat_summary使用现有的组成员身份将摘要行添加到绘图中。我在绘制线条时遇到了麻烦,虽然我理解了这个问题,但仍想不出如何避免引起问题的方法。

一个例子:

library(ggplot2)
df <- data.frame(low=c(20,24,18,16), 
                 mid=c(60,61,48,45), 
                 high=c(80,75,81,83), 
                 category=factor(seq(1:4)), 
                 membership=factor(c(1,1,2,2)))

p <- ggplot(df, aes(x=category, y=mid)) +
  geom_linerange(aes(ymin=low, ymax=high)) +
  geom_point(shape=95, size=8)
p

这将产生四个类别的每个图表: enter image description here

第一步是使用stat_summary添加一行以显示yminyymax的均值,就像这样:

p + 
  stat_summary(data=df, aes(x="Aggregate", ymin=mean(low), y=mean(mid), ymax=mean(high)), 
               fun.data="mean", geom="linerange", inherit.aes=F) +
  stat_summary(data=df, aes(x="Aggregate", y=mid), fun.y="mean", geom="point", 
               size=8, shape=95)

enter image description here

但是,当我尝试使用df中的成员资格在组内产生均值时,我遇到了linerange的问题(尽管point很好)。

p + 
  stat_summary(data=df, aes(x="Aggregates", ymin=low, y=mid, ymax=high, group=membership), 
               fun.ymin="mean", fun.y="mean", fun.ymax="mean", geom="linerange", 
               inherit.aes=F, position_dodge(0.5))
  stat_summary(data=df, aes(x="Aggregates", y=mid, group=membership), 
               fun.y="mean", geom="point", size=8, shape=95, position_dodge(0.5))

enter image description here

我从ggplot_build(p)知道ymin = y = ymax,这就是情节上什么都没显示的原因。但是,如果我使用fun.data而不是fun.ymin / fun.ymax,则会出现关于不需要yminymax美观的错误。

$data[[3]]
      x group ymin    y ymax 
1 5.125     2 46.5 46.5 46.5 
2 4.875     1 60.5 60.5 60.5 

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

在将数据框传递到ggplot()进行绘图之前,您可能会发现计算 之前的分组均值更容易。以下是一种可能的方法:

library(dplyr)

df %>%
  rbind(df %>%
          mutate(category = "Aggregate") %>%
          group_by(category, membership) %>%
          summarise_all(mean) %>% # calculate mean for low / mid / high by group
          ungroup() %>%
          select(colnames(df))) %>% #reorder columns to match the original df
  ggplot(aes(x = category, y = mid, ymin = low, ymax = high,
             colour = membership)) +
  geom_linerange(position = position_dodge(width = 0.5)) +
  geom_point(shape = 95, size = 8,
             position = position_dodge(width = 0.5))

(我添加了color = membership,以使这些组在视觉上更加鲜明。)

plot