【问题标题】:How to take the slope of the lm regression in the ggplot如何在ggplot中取lm回归的斜率
【发布时间】:2026-02-03 03:00:01
【问题描述】:

我使用 ggplot 在 x 和 y 变量之间绘制了一个绘图,并且特别是以下代码:

ggplot(data = dataset, aes(x = X, y = log_Y, colour = Year)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE)

有什么方法可以取 lm 回归创建的直线的斜率?

提前致谢!

【问题讨论】:

  • ggplot 实际上只是用于可视化。如果您需要使用回归结果,您应该在 ggplot 之外拟合模型。

标签: r ggplot2 gradient lm


【解决方案1】:

使用broom 包,它简化了提取模型数据的过程。例如:

library(broom)
library(dplyr)

fit <- lm(mpg ~ cyl, data = mtcars)
summary(fit)

fit %>%
    tidy() %>%
    filter(term == "cyl") %>%
    pull(estimate)

【讨论】:

  • 非常感谢!