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

如何在R语言的连续数据散点图中添加分类分组?

在GAM拟合散点图中添加Season分类变量区分

嘿,想要在你现有的灰海豹数量散点图里加入Season分类变量来区分不同组的数据点?这其实很简单,我给你两种常用的实现方式,你可以按需选择:

方法1:用颜色区分不同Season

你只需要给每个Season指定专属颜色,然后在绘图时让点的颜色对应其Season属性,最后加上图例说明即可。修改后的代码如下:

# 确保Season是因子类型(如果还不是的话)
R_Count$Season <- as.factor(R_Count$Season)

# 为每个季节定义颜色(可根据你的季节名称调整)
season_colors <- c("Spring" = "#2E8B57", "Summer" = "#FFD700", "Autumn" = "#FF8C00", "Winter" = "#1E90FF")

# 绘制散点图,按Season分配颜色
plot(Total ~ Obsv_time, data = R_Count, 
     ylab = "Total", xlab = "Observation Time (Days)", 
     pch = 20, cex = 1, bty = "l",
     col = season_colors[R_Count$Season]) 

# 添加GAM拟合曲线
lines(R_Count$Obsv_time, fitted(gam.tot2), lwd = 2)

# 添加图例,说明颜色对应的季节
legend("topright", legend = levels(R_Count$Season), 
       col = season_colors, pch = 20, bty = "n", title = "Season")

方法2:同时用颜色和形状区分(更适合多季节场景)

如果担心颜色区分不够直观,还可以结合点的形状(pch参数)来强化分类效果:

# 确保Season是因子类型
R_Count$Season <- as.factor(R_Count$Season)

# 定义颜色和形状映射
season_colors <- c("Spring" = "#2E8B57", "Summer" = "#FFD700", "Autumn" = "#FF8C00", "Winter" = "#1E90FF")
season_shapes <- c("Spring" = 20, "Summer" = 17, "Autumn" = 15, "Winter" = 16)

# 绘制散点图
plot(Total ~ Obsv_time, data = R_Count, 
     ylab = "Total", xlab = "Observation Time (Days)", 
     cex = 1, bty = "l",
     col = season_colors[R_Count$Season],
     pch = season_shapes[R_Count$Season]) 

# 添加GAM拟合曲线
lines(R_Count$Obsv_time, fitted(gam.tot2), lwd = 2)

# 添加图例
legend("topright", legend = levels(R_Count$Season), 
       col = season_colors, pch = season_shapes, bty = "n", title = "Season")

小提示:如果你的Season类别名称和我示例里的不一样,记得同步修改season_colors和season_shapes里的键名哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:05:40