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

分组数据时为geom_smooth定义不同视觉属性

给不同搅拌组的geom_smooth线条设置差异化视觉属性

要让不同mix组的拟合线条拥有不同的视觉样式(颜色、线型等),核心是把视觉属性映射到mix变量,而非硬编码统一样式。具体修改如下:

修改后的代码

M3 <- ggplot(subset(VFA2, VFA %in% "HPr"),  
             aes(x = Time, y = value, group = mix, shape = Test, colour = Test)) +
  geom_point(size = 6, colour = "purple4") +
  labs(x = "厌氧时间 (h)\n 持续搅拌", y = "HPr浓度\n(mg HPr/L)") +
  theme(panel.background = element_rect(fill = "White", colour = "grey"),
        panel.grid.major = element_line(color = 'grey'), 
        legend.position="bottom", 
        text= element_text(size = 28, family = "Arial")) +
  scale_x_discrete(breaks = factor(VFA2$Time), expand = c(-0.25,2)) +
  scale_y_continuous(limits = c(-0.25, 60),breaks = c(0, 10,20, 30, 40, 50, 60)) +
  scale_shape_manual(values = c(0,1,2,5,7,13,14,9)) +
  # 为geom_smooth绑定mix组的视觉属性映射
  geom_smooth(method= "gam", formula = y~poly(x,4), se = F, 
              aes(colour = mix, linetype = mix)) +
  # 自定义每个mix组的颜色(键名需匹配数据中mix列的实际取值)
  scale_colour_manual(values = c("搅拌组1" = "#E64B35", "搅拌组2" = "#4DBBD5", "搅拌组3" = "#00A087")) +
  # 自定义每个mix组的线型(键名需匹配数据中mix列的实际取值)
  scale_linetype_manual(values = c("搅拌组1" = "solid", "搅拌组2" = "dashed", "搅拌组3" = "dotted"))

关键改动说明

  • 将colour和linetype参数移至geom_smooth的aes()内部,让ggplot自动按mix分组生成对应样式的线条。
  • 保留原代码中geom_point的固定紫色,避免点与线条颜色混淆;若需要点也按mix分组变色,可移除geom_point里的colour = "purple4",并调整aes中的映射逻辑。
  • 通过scale_colour_manual和scale_linetype_manual可精准定义每个搅拌组的视觉样式,values中的键名必须与数据中mix列的实际取值完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:40:32