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

R时间序列绘图中autoplot加scale_y_continuous后geom_abline消失问题

你遇到的回归线消失问题,是因为scale_y_continuous的limits参数会在绘图前提前剔除所有超出y轴范围的数据,包括geom_abline生成的直线点位,所以直线被完全裁剪无法显示。

要解决这个问题,你需要改用coord_cartesian函数调整y轴范围,该函数仅缩放可视化视口,不会对底层数据做裁剪,回归线即可正常显示。

正确代码如下:

library(fpp2)
library(forecast)
library(ggplot2)

# 拟合线性模型
m400 <- tslm(mens400 ~ tm400)

# 绘图
autoplot(mens400) +
  geom_abline(slope = m400$coefficients[2], intercept = m400$coefficients[1], colour = "red") +
  coord_cartesian(ylim = c(40, 60))

你也可以直接使用geom_smooth自动拟合回归线,无需手动提取系数,代码更简洁:

autoplot(mens400) +
  geom_smooth(method = "lm", se = FALSE, colour = "red") +
  coord_cartesian(ylim = c(40, 60))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 13:54:03