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

在ggplot2中修改图例标题遇重复图例问题求助

解决ggplot图例标题重复问题

问题原因

你在代码中同时将color、shape、linetype三个美学属性绑定到了sSkills变量,但仅在labs()中修改了color的标题,shape和linetype的标题仍为默认的sSkills。ggplot会将标题不一致的美学映射拆分为多个图例,因此出现了重复图例。

解决方案

方案1:在labs()中统一所有相关美学属性的标题

直接在labs()里同时指定color、shape、linetype的标题为“Social Skills”,ggplot会自动将绑定同一变量的美学映射合并为单个图例:

intPlot <- ggplot(IntPoints2Plot, aes(sComplex, sPerform, color = sSkills, shape = sSkills, group = sSkills)) +
  geom_line(aes(linetype = sSkills)) +
  geom_point(size=5) + 
  ylim(12,15) + 
  theme(axis.text=element_text(size=11), 
        axis.title=element_text(size=11),
        legend.title=element_text(size=11),
        legend.text=element_text(size=11)) +
  labs(x = "Social Complexity", 
       y = "Social Performance", 
       color = "Social Skills",
       shape = "Social Skills",
       linetype = "Social Skills") +
  theme_apa(x.font.size = 11, y.font.size = 11, legend.use.title = T)

intPlot

方案2:使用guides()统一设置图例标题

通过guides()函数一次性为所有关联的美学映射设置相同标题,代码更简洁:

intPlot <- ggplot(IntPoints2Plot, aes(sComplex, sPerform, color = sSkills, shape = sSkills, group = sSkills)) +
  geom_line(aes(linetype = sSkills)) +
  geom_point(size=5) + 
  ylim(12,15) + 
  theme(axis.text=element_text(size=11), 
        axis.title=element_text(size=11),
        legend.title=element_text(size=11),
        legend.text=element_text(size=11)) +
  labs(x = "Social Complexity", 
       y = "Social Performance") +
  guides(color = guide_legend(title = "Social Skills"),
         shape = guide_legend(title = "Social Skills"),
         linetype = guide_legend(title = "Social Skills")) +
  theme_apa(x.font.size = 11, y.font.size = 11, legend.use.title = T)

intPlot

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:50:19