如何在ggplot图例中添加标注为LMWL的geom_abline
解决ggplot中geom_abline图例重复问题
问题根源在于你的全局aes中包含了color = category,geom_abline会继承这个映射,为每个category生成一条重叠的线条,导致图例混乱。要添加单独的"LMWL"黑色线条图例,可按以下方式修改代码:
修改后的完整代码
ggplot(df_merge_iso, aes(x = d18O, y = d2H, label = month)) + labs( x = expression(paste(delta^{18}, "O (‰)")), y = expression(paste(delta^{2}, "H (‰)")) ) + # 将color和shape映射移到geom_point内部,避免其他图层继承 geom_point(aes(color = category, shape = category), size = 1, stroke = 1) + theme_minimal() + theme( axis.text = element_text(size = 12, color = "black"), axis.title = element_text(size = 12, color = "black") ) + scale_color_manual( name = "", values = c( "A" = "#0015f0", "B" = "#6AC4FF", "C" = "#4B8CEB", "D" = "#FF7E5F", "E" = "#FFB300", "F" = "#E75007" )) + scale_shape_manual( name = "", values = c( "A" = 2, "B" = 1, "C" = 21, "D" = 3, "E" = 4, "F" = 6 )) + geom_text_repel( vjust = -1, hjust = 0.5, size = 2, show.legend = FALSE, box.padding = 0.2 ) + # 为geom_abline添加自定义linetype映射,触发单独图例 geom_abline(aes(linetype = "LMWL"), slope = lmwl_slope_wgt, intercept = lmwl_intercept_wgt, colour = "black", size = 0.5) + # 定义线条样式 scale_linetype_manual( name = "", values = c("LMWL" = "solid") ) + # 调整图例顺序,让线条图例优先显示 guides( linetype = guide_legend(order = 1), color = guide_legend(order = 2), shape = guide_legend(order = 2) )
关键修改说明
- 隔离映射范围:把
color和shape的映射从全局aes移到geom_point内部,确保只有点图层使用这些分类映射,geom_abline不会继承后生成重复线条。 - 生成单独图例:在
geom_abline的aes中定义linetype = "LMWL",用自定义的分类值触发图例项,再通过scale_linetype_manual指定线条样式。 - 优化图例排版:用
guides调整图例的显示顺序,让线条图例和点图例的排列更合理。
如果你不想调整全局aes,也可以给geom_abline加上inherit.aes = FALSE参数,同样能避免继承分类映射,代码如下:
# 保留全局aes的版本 ggplot(df_merge_iso, aes(x = d18O, y = d2H, color = category, shape = category, label = month)) + labs( x = expression(paste(delta^{18}, "O (‰)")), y = expression(paste(delta^{2}, "H (‰)")) ) + geom_point(size = 1, stroke = 1) + theme_minimal() + theme( axis.text = element_text(size = 12, color = "black"), axis.title = element_text(size = 12, color = "black") ) + scale_color_manual( name = "", values = c( "A" = "#0015f0", "B" = "#6AC4FF", "C" = "#4B8CEB", "D" = "#FF7E5F", "E" = "#FFB300", "F" = "#E75007" )) + scale_shape_manual( name = "", values = c( "A" = 2, "B" = 1, "C" = 21, "D" = 3, "E" = 4, "F" = 6 )) + geom_text_repel( vjust = -1, hjust = 0.5, size = 2, show.legend = FALSE, box.padding = 0.2 ) + geom_abline(aes(linetype = "LMWL"), slope = lmwl_slope_wgt, intercept = lmwl_intercept_wgt, colour = "black", size = 0.5, inherit.aes = FALSE) + scale_linetype_manual( name = "", values = c("LMWL" = "solid") ) + guides( linetype = guide_legend(order = 1), color = guide_legend(order = 2), shape = guide_legend(order = 2) )
内容的提问来源于stack exchange,提问作者crtnnn
相关产品推荐
相关产品推荐

