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

R中ggplot2无法绘制趋势线问题求助

解决ggplot2无法显示线性趋势线的问题

可能的原因及解决步骤

1. 检查year列的数据类型

如果year是**因子(factor)**而非数值型(numeric/integer),geom_smooth(method=lm)无法正确拟合线性模型(线性回归要求自变量为连续数值)。

  • 先检查数据类型:
class(atemp_sum$year)
  • 如果结果显示为factor,将其转换为数值型:
atemp_sum$year <- as.numeric(as.character(atemp_sum$year))

(注意:直接用as.numeric(atemp_sum$year)会把因子转成水平序号,而非原始年份数值)

2. 验证线性回归模型的实际结果

用你提供的数据拟合线性回归,会发现趋势线的斜率非常小且为负:

lm(mean ~ year, data = atemp_sum)

输出结果:

Call:
lm(formula = mean ~ year, data = atemp_sum)

Coefficients:
(Intercept)         year  
   163.2286      -0.0710  

这说明你的数据中温度没有上升趋势,反而每年平均下降约0.07℃。趋势线因斜率极小,可能和散点分布重叠导致视觉上“消失”,但实际是存在的。

3. 重新运行绘图代码

完成数据类型转换后,执行你的绘图代码:

ggplot(atemp_sum, aes(x = year, y = mean)) + 
  labs(x = "Year", y = "Temperature C") + 
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, col='red', size=2)

此时应该能看到红色的趋势线(呈现平缓下降的趋势)。


内容的提问来源于stack exchange,提问作者Rachel K Guy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:35:26