使用ggplot2将组均值线添加到barplot

使用ggplot2将组均值线添加到barplot

本文介绍了使用ggplot2将组均值线添加到barplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用geom_col()生成一个带有颜色分隔的两个类的barplot.然后,我尝试为每个班级添加一条平均线.

I generate a barplot with geom_col() with two classes separated by color. Then I try to add a mean line for each class.

这就是我想要得到的:

但是在下面的代码中,平均线是每个小节独立地放在组参数中的内容.

But with the code below the mean line is for each bar independently what I put to group argument.

以下是可重现的示例:

library(tidyverse)

df = data.frame(
  x = 1:10,
  y = runif(10),
  class = sample(c("a","b"),10, replace=T) %>% factor()
) %>%
  mutate(x = factor(x, levels=x[order(class, -y)]))

ggplot(df, aes(x, y, fill=class)) +
geom_col() +
stat_summary(fun.y = mean, geom = "errorbar",
             aes(ymax = ..y.., ymin = ..y.., group = class),
             width = 1, linetype = "solid")

请告诉我我在做什么错.还是任何其他方法(使用ggplot)来实现这一目标?

Please tell me what I'm doing wrong. Or any other way (with ggplot) to achieve this?

推荐答案

我使用@geom_errorbar将@bouncyball的解决方案与我的原始方法结合在一起.

I combined the solution from @bouncyball with my original approach using `geom_errorbar.

这是代码:

df.mean = df %>%
  group_by(class) %>%
  mutate(ymean = mean(y))

ggplot(df, aes(x, y, fill=class)) +
  geom_col() +
  geom_errorbar(data=df.mean, aes(x, ymax = ymean, ymin = ymean),
               size=0.5, linetype = "longdash", inherit.aes = F, width = 1)

唯一的问题是,这种方法不是生成单行,而是生成许多行对象,这些对象可以在编辑绘图时看到,例如在Adobe Illustrator中.但我可以忍受.

The only problem is that instead of single line this approach generate a lot of line objects which can be seen when editing the plot, for example, in Adobe Illustrator. But I can live with it.

这篇关于使用ggplot2将组均值线添加到barplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:27