在没有截距ggplot的情况下将回归线文本添加到图形中

Adding regression line text to graph with no intercept ggplot

我想将回归线方程和 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。有解决办法吗?

在这种简单的情况下(没有分面或分组),您不需要创建新的 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()

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

题外话:从统计的角度来看,不带截距的回归是合理的是非常罕见的。

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