You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并ggplot2中分别映射的线型、大小、形状、颜色图例

ggplot2多图例合并解决方法

你遇到的图例拆分问题是因为不同美学映射(颜色、线型、形状、大小)的scale没有设置统一名称,ggplot2默认会为每个不同名称的美学映射生成独立图例。只需做两处修改即可合并图例:

  1. 为所有scale_xxx_manual设置完全相同的name参数,可自定义图例标题或者设为NULL隐藏标题
  2. 保持各scale中分类命名(Rate、Target)完全匹配,你当前的分类命名已经符合要求,无需调整

修改后的完整绘图代码

ggplot(d,aes(x=month,y=percent)) + 
  geom_point(aes(x=month,y=percent,color="Rate",shape="Rate"), size=2) +
  geom_text(aes(label = paste(format(percent, digits = 4, format = "f"), "‰")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = percent, group=1, color="Rate",linetype = "Rate",size="Rate")) + 
  geom_hline(aes(yintercept=1,color="Target",linetype="Target",size="Target"))+
  scale_y_continuous(breaks = seq(0,1.1,0.2), 
                     labels = paste0(seq(0,1.1,0.2)," ‰")) +
  expand_limits(y = c(0, 1.1)) +
  labs(y="", x="") + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  # 所有scale都设置相同的name,这里设为NULL隐藏图例标题,和你预期效果一致
  scale_colour_manual(name = NULL, values = c(Rate = "#00BFC4", Target = "#F8766D")) +
  scale_linetype_manual(name = NULL, values = c(Rate = "solid", Target = "dashed")) +
  scale_shape_manual(name = NULL, values = c(Rate = 16, Target = NA)) +
  scale_size_manual(name = NULL, values = c(Rate = 1, Target = .7)) +
  theme(legend.key=element_blank(),legend.position="bottom") 

运行上述代码即可得到你预期的合并后图例效果。


内容的提问来源于stack exchange,提问作者Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:48:02