我使用 geom_col() 生成一个条形图,其中两个类由颜色分隔。然后我尝试为每个类(class)添加一条平均线。
这是我想得到的:
但是,平均线下方的代码是针对每个条形独立的,我将其放入组参数中。
这是一个可重现的示例:
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)来实现这一目标?
最佳答案
我使用`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)
唯一的问题是,这种方法不是单线,而是生成了许多在编辑绘图时可以看到的线对象,例如,在 Adobe 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/