ggplot2散点图重复图例及误差栏异常问题求助
ggplot2绘图问题:重复图例与误差栏异常解决思路
我用ggplot2绘图时遇到两个问题:
- 无法消除重复的图例,推测是操作失误导致;
- 误差栏显示异常,持续弹出提示:
No summary function supplied, defaulting to mean_se()。
绘图效果:
原代码:
data %>% ggplot(., aes(x = X, y = Y)) + stat_summary(aes(group = LANGUAGE), position = position_dodge(width = 0)) + stat_summary(fun = mean, shape = 4) + stat_summary(aes(group = LANGUAGE, linetype = LANGUAGE, color = LANGUAGE), geom = "line", size = 1, position = position_dodge(width = 0)) + scale_color_manual(values = c(L1 = "yellow", L2 = "green"), name = "Language:") + theme_bw() + theme(legend.position = "right", legend.background = element_rect(color = "black"), #bloco com legendas axis.text.x = element_text(angle = 0, hjust = 0.5, face = "bold"), # legenda de baixo plot.title = element_text(hjust = 0.5, face = "bold"), axis.text.y = element_text(face = "bold"))
变量说明:分类变量LANGUAGE包含L1和L2两个水平。
问题原因与解决方法
1. 重复图例问题
重复图例的根源是多次调用stat_summary时,部分图层单独设置了color、linetype等映射,而全局aes没有统一配置,导致ggplot为每个带映射的图层都生成了图例。
解决方式:
- 将
group、color、linetype这些共享的映射移到全局的ggplot(aes())中,让所有图层继承同一套映射; - 对不需要生成图例的图层(比如仅绘制点的图层),添加
show.legend = FALSE参数。
2. 误差栏异常与提示信息
第一个stat_summary既没指定geom类型,也没明确误差计算函数,ggplot默认用mean_se()计算并绘制误差,因此弹出提示。同时position_dodge(width=0)等于没有偏移,误差栏会和其他元素重叠,导致显示异常。
解决方式:
- 明确指定
geom = "errorbar"来绘制误差栏,并用fun.data = mean_se明确误差计算逻辑,消除提示; - 给所有需要分组偏移的图层设置相同的
position_dodge(width = 0.5),保证误差栏、点、线对齐不重叠。
修改后的完整代码
data %>% ggplot(., aes(x = X, y = Y, group = LANGUAGE, color = LANGUAGE, linetype = LANGUAGE)) + # 绘制误差栏,指定计算函数与偏移宽度 stat_summary(fun.data = mean_se, geom = "errorbar", position = position_dodge(width = 0.5), width = 0.2) + # 绘制均值点,关闭图例避免重复 stat_summary(fun = mean, shape = 4, position = position_dodge(width = 0.5), show.legend = FALSE) + # 绘制分组连线,继承全局映射 stat_summary(fun = mean, geom = "line", size = 1, position = position_dodge(width = 0.5)) + scale_color_manual(values = c(L1 = "yellow", L2 = "green"), name = "Language:") + theme_bw() + theme(legend.position = "right", legend.background = element_rect(color = "black"), axis.text.x = element_text(angle = 0, hjust = 0.5, face = "bold"), plot.title = element_text(hjust = 0.5, face = "bold"), axis.text.y = element_text(face = "bold"))
内容的提问来源于stack exchange,提问作者Larissa Cury
相关产品推荐
相关产品推荐

