ggplot中stat_summary的group参数解析及图例添加问题
你想要按mouse_ID着色展示A、B处理间的个体差异,同时绘制忽略mouse_ID的整体均值连线,已实现预期效果,但对代码中的group参数和图例添加有疑问,以下是针对三个问题的解答:
示例数据集构建代码
df <- data.frame(x = c(1, 2, 4, 3, 1.5, 4, 3, 2, 6, 3, 4, 2, 5, 0, 1, 3, 5, 4), factor_col = c(rep("A", 18)), mouse_ID = c(1:18)) df2 <- data.frame(x = df$x + 3, factor_col = c(rep("B", 18)), mouse_ID = c(1:18)) Table = bind_rows(df, df2) Table$mouse_ID = as.factor(Table$mouse_ID) Table$factor_col = as.factor(Table$factor_col)
绘图代码
(b = Table %>% ggplot(aes(x=factor_col, y=x, color = mouse_ID, group =mouse_ID)) + geom_point() + geom_line() + stat_summary(aes(y = x, group = factor_col), fun.y=mean, colour="black", geom="line", group=1, size=3) + xlab("Manipulations") + #ylim(0,1)+ ylab("x-value") + labs(title = "")+ theme_Publication() + theme(axis.text.x = element_text(angle = 45, hjust = 1)))
问题解答
stat_summary中的group=1是什么含义?
在ggplot2中,group参数用于指定数据的分组规则,决定哪些数据点会被归为一组进行计算或绘图。设置group=1意味着把整个数据集当作一个单一分组来处理。这里你需要绘制的是所有样本在A、B两个处理下的整体均值连线,用group=1就能打破全局继承的mouse_ID分组规则,让stat_summary对所有数据按factor_col计算均值,再把两个均值点连接成线。为何要在stat_summary中重复设置group参数?
全局ggplot的aes里设置了group=mouse_ID,这个分组规则会被所有图层默认继承。如果stat_summary不重新指定group,就会按每个mouse_ID分别计算均值,画出来的是每个个体在A、B间的连线,而非你想要的整体均值线。你代码里先在stat_summary的aes中写了group=factor_col,又在图层参数里加了group=1,本质都是为了覆盖全局的分组规则,确保stat_summary按你需要的方式(整体为一组)计算均值。不过这里group=1的优先级更高,最终生效的是这个设置。如何在颜色图例中添加“Means”条目?
目前你直接给均值线设置了colour="black",没有将颜色映射到aes中,所以不会出现在图例里。要添加这个条目,需要把颜色映射到aes,再手动指定颜色:
- 修改stat_summary的代码,将颜色映射为固定字符串:
stat_summary(aes(y = x, color="Means"), fun=mean, geom="line", group=1, size=3) - 添加
scale_color_manual来指定所有mouse_ID的颜色和“Means”对应的黑色:scale_color_manual( values = c( setNames(hcl.colors(18, "viridis"), levels(Table$mouse_ID)), "Means" = "black" ) )
这样图例就会包含所有mouse_ID的颜色条目,以及标注为“Means”的黑色条目。
内容的提问来源于stack exchange,提问作者Chiara Toschi

