r - 使用 ggplot2 将组平均线添加到条形图

标签 r ggplot2 bar-chart

我使用 geom_col() 生成一个条形图,其中两个类由颜色分隔。然后我尝试为每个类(class)添加一条平均线。

这是我想得到的:

Desired output

但是,平均线下方的代码是针对每个条形独立的,我将其放入组参数中。

这是一个可重现的示例:

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

What I get

请告诉我我做错了什么。或者任何其他方式(使用ggplot)来实现这一目标?

最佳答案

我使用`geom_errorbar 将@bouncyball 的解决方案与我原来的方法结合起来。
这是代码:

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)
enter image description here
唯一的问题是,这种方法不是单线,而是生成了许多在编辑绘图时可以看到的线对象,例如,在 Adob​​e Illustrator 中。但我可以忍受它。
更新
另一种解决方案 - 更简单,没有上述问题。再次基于@bouncyball 的代码。
df.mean = df %>% 
  group_by(class) %>% 
  summarise(ymean = mean(y), x1 = x[which.min(x)], x2 = x[which.max(x)]) %>% 
  ungroup()

ggplot(df) +
  geom_col(aes(x, y, fill = class)) +
  geom_segment(data = df.mean,
               aes(x = as.integer(x1) - 0.5, xend = as.integer(x2) + 0.5,
                   y = ymean, yend = ymean),
               size=1, linetype = "longdash", inherit.aes = F)

关于r - 使用 ggplot2 将组平均线添加到条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882335/

相关文章:

javascript - 如何在条形图的条形上添加文本?

r - 将因子类型时间转换为分钟数

r - 如何整齐地对齐堆叠条形图标签,使条形的每一侧对齐方式不同?

text - 如何增加 MPAndroid 条形图顶部文本值的大小?

r - ggplot 中未出现的行

r - 带有导入图像的自定义图例

python - 使用 matplotlib 和子图绘制多个条形图

r - 在ff中创建大型矩阵

r - ggplot guide_legend 参数将连续图例更改为离散图例

r - 重新排序行以具有重复序列的有效方法?