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

如何修复stat_poly_eq中的斜率计算错误?实际斜率不符问题解决

问题修正方案

你的代码核心错误是没有调用stat_poly_eq()图层,反而错误地在全局aes中构造标签,导致无法正确计算和展示回归方程。以下是修正后的完整代码:

library(ggplot2)
library(ggpmisc)

# 数据
df <- structure(list(Variety = c("Sultana - MG 000", "ES Pallador - MG I", "Isidor - MG I", "Santana - MG I/II", "Blancas - MG II", "Ecudor - MG II"), 
                     FTSWt2017 = c(0.54, 0.47, 0.41, 0.18, 0.25, 0.18), 
                     FTSWt2021 = c(0.32, 0.27, 0.35, 0.29, 0.22, 0.32)), 
                class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -6L))

ggplot(df, aes(x = FTSWt2017, y = FTSWt2021)) +
  geom_point(aes(color = Variety)) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, color = "black") +
  geom_abline(intercept = 0, slope = 1, color = "gray", linetype = "dashed", size = 0.5) +
  # 正确添加回归方程和R²的图层
  stat_poly_eq(
    formula = y ~ x,
    aes(label = paste(after_stat(eq.label), after_stat(rr.label), sep = "~~")),
    parse = TRUE, # 解析数学表达式
    label.x = "right", # 标签位置
    label.y = "top"
  )

关键修正点:

  • 移除了原代码中错误的aes(label=...)块,改用stat_poly_eq()专门处理回归方程的计算与展示
  • stat_poly_eq()需要指定formula与主图层一致,通过after_stat()获取计算后的方程(eq.label)和R²(rr.label)
  • parse=TRUE确保数学表达式(如下标、等号)正确渲染

运行修正后的代码,得到的回归方程为y = 0.10x + 0.28,R²≈0.02,斜率远小于0.5,符合你的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:25:32