【问题标题】:Adding regression line text to graph with no intercept ggplot将回归线文本添加到没有截距 ggplot 的图形中
【发布时间】:2016-06-26 18:49:56
【问题描述】:

我想将回归线方程和 r 平方值添加到我的ggplot2 散点图中。

我发现了一个类似的问题,它给出了下面的代码,但是当我通过拦截强制回归时它不起作用:

library(devtools)
source_gist("524eade46135f6348140")
df = data.frame(x = c(1:100))
df$y = 2 + 5 * df$x + rnorm(100, sd = 40)
ggplot(data = df, aes(x = x, y = y, label=y)) +
  stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE, formula=y~x-1) +
  geom_smooth(method="lm",se=FALSE, formula=y~x-1) +
  geom_point()

通过添加formula=y~x-1,显示的文本将系数显示为截距,截距为NA。有解决办法吗?

【问题讨论】:

  • 我不是在寻找一些未知的要点。如果您在 SO 问题中找到代码,请链接该问题。更好的是,只需在您的问题中提供stat_smooth_func 的源代码即可。
  • 上面的链接是我找到问题中引用的代码的地方

标签: r text ggplot2 regression lm


【解决方案1】:

一个选项是geom_smooth(method="lm",formula=y~0+x)

【讨论】:

    【解决方案2】:

    在这种简单的情况下(没有分面或分组),您不需要创建新的stat_*。你可以这样做:

    fit <- lm(y ~ x - 1, data = df)
    ggplot(data = df, aes(x = x, y = y, label=y)) +
      stat_function(fun = function(x) predict(fit, newdata = data.frame(x = x)),
                    color = "blue", size = 1.5) +
      annotate(label = sprintf("y = %.3f x\nR² = %.2f", coef(fit), summary(fit)$r.squared),
               geom = "text", x = 25, y = 400, size = 12) +
      geom_point()
    

    当然,来自 gist 的 stat_* 函数很容易通过原点进行回归调整。

    题外话:从统计的角度来看,没有截距的回归是非常罕见的。

    【讨论】:

    • 在我的数据上下文中,一个变量的值为 0,意味着另一个变量必须为 0。无论如何,当通过我的原点回归时,r 平方值显着提高数据。感谢您的回答 - 成功了!
    猜你喜欢
    • 2021-10-25
    • 2022-01-09
    • 2021-05-21
    • 2021-04-16
    • 2021-10-25
    • 2017-10-23
    • 2013-03-16
    • 2018-08-28
    相关资源
    最近更新 更多