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

如何使用ggplot2为分组趋势线设置不同颜色?

问题描述

使用geom_jitter和geom_smooth绘制图表时,已按Patch_type组指定点的填充颜色,但无法设置趋势线的颜色,当前所有趋势线颜色一致,希望将其改为不同颜色。

现有代码:

ggplot(data=data, aes(x=Max, y=count, group=Patch_type,fill=factor(Patch_type)))+
  geom_jitter(color='black', shape=21, size=4)+
  labs(title = "Abundance of moths by maximum temperature", x="Temperature", y="Abundance")+
  scale_fill_manual(values=c("#EDF8B1", "#7FCDBB", "#2D7FB8"), name="Patch Type")+
  theme(text = element_text(size = 14))+
  geom_smooth(method="glm")

尝试过的方法:

  • 将scale_fill_manual参数移到末尾,未生效;
  • 在ggplot参数中使用color=,但无法分别指定点和趋势线的颜色。
解决方案

问题核心是geom_jitter用的是fill美学映射(对应带填充的点形状shape=21),而geom_smooth默认使用color美学映射,二者是独立的。要让趋势线按Patch_type分色,需给color绑定分组变量,同时保持点的边框颜色为黑色。

修改后的代码(方式一)

ggplot(data=data, aes(x=Max, y=count, group=Patch_type))+
  # 点的填充用fill映射,边框固定为black
  geom_jitter(aes(fill=factor(Patch_type)), color='black', shape=21, size=4)+
  labs(title = "Abundance of moths by maximum temperature", x="Temperature", y="Abundance")+
  # 统一设置填充色和线条色,保持视觉风格一致
  scale_fill_manual(values=c("#EDF8B1", "#7FCDBB", "#2D7FB8"), name="Patch Type")+
  scale_color_manual(values=c("#EDF8B1", "#7FCDBB", "#2D7FB8"), name="Patch Type")+
  theme(text = element_text(size = 14))+
  # 趋势线用color映射分组
  geom_smooth(aes(color=factor(Patch_type)), method="glm")

修改后的代码(方式二)

也可以把fill和color放到全局美学映射中,再在geom_jitter里覆盖color为黑色:

ggplot(data=data, aes(x=Max, y=count, group=Patch_type, fill=factor(Patch_type), color=factor(Patch_type)))+
  geom_jitter(color='black', shape=21, size=4)+ # 覆盖color为黑色,保留fill映射
  labs(title = "Abundance of moths by maximum temperature", x="Temperature", y="Abundance")+
  scale_fill_manual(values=c("#EDF8B1", "#7FCDBB", "#2D7FB8"), name="Patch Type")+
  scale_color_manual(values=c("#EDF8B1", "#7FCDBB", "#2D7FB8"), name="Patch Type")+
  theme(text = element_text(size = 14))+
  geom_smooth(method="glm")

关键说明

  • 两种方式都能实现:点的填充按组变色、边框为黑色,趋势线按组变色的效果;
  • 用scale_fill_manual和scale_color_manual设置相同颜色值,保证图例与视觉风格统一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:53:31