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

ggplot中使用scale_fill_discrete修改图例标题后重复问题求助

解决ggplot图例重复的问题

Hey there! 你的问题出在同时在aes()里映射了color和fill两个美学属性到同一个变量ses3,但只调整了scale_fill_discrete()的设置,没同步处理color对应的刻度,所以ggplot生成了两个独立的图例(一个对应填充色,一个对应线条/边界色)。

要解决这个问题,有两种简单的方法:

方法一:同步设置fill和color的刻度,让ggplot自动合并图例

既然color和fill都对应同一个分类变量,我们可以让它们的标题、breaks和labels完全一致,ggplot就会自动把两个图例合并成一个:

plots[[j]] <- ggplot(cdat, aes(x = whr, y = perc, 
                               group = factor(ses3), 
                               color = factor(ses3), 
                               fill = factor(ses3))) +
  theme_bw() +
  geom_area(alpha = 0.5) +
  # 同时设置fill和color的刻度,参数完全一致
  scale_fill_discrete(name = "SES", breaks = c("0", "1"), labels = c("Low", "High")) +
  scale_color_discrete(name = "SES", breaks = c("0", "1"), labels = c("Low", "High")) +
  theme(plot.title = element_text(hjust = 0, size = 10, face = "bold")) +
  labs(y = "Density", x = "Treatment hrs (in 3 hr units)") +
  theme(text = element_text(size = 10, hjust = 0.5))

方法二:用guides()函数手动合并或移除多余图例

如果不想重复写两次scale设置,也可以用guides()函数指定其中一个美学属性的guide,让它和另一个共享:

plots[[j]] <- ggplot(cdat, aes(x = whr, y = perc, 
                               group = factor(ses3), 
                               color = factor(ses3), 
                               fill = factor(ses3))) +
  theme_bw() +
  geom_area(alpha = 0.5) +
  scale_fill_discrete(name = "SES", breaks = c("0", "1"), labels = c("Low", "High")) +
  # 让color的图例和fill的保持一致,或者直接移除color图例
  guides(color = guide_legend(title = "SES", breaks = c("0", "1"), labels = c("Low", "High"))) +
  # 或者直接隐藏color图例:guides(color = "none")
  theme(plot.title = element_text(hjust = 0, size = 10, face = "bold")) +
  labs(y = "Density", x = "Treatment hrs (in 3 hr units)") +
  theme(text = element_text(size = 10, hjust = 0.5))

两种方法都能让你只看到一个标题为"SES"、取值为"Low"和"High"的图例,选哪种都可以~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:48:12