lm()的ggplot与方程式

时间:2019-06-29 07:55:56

标签: r ggplot2 equation lm

如果在截距和斜率上没有“ c()”字符,我将无法在绘图上绘制线性模型文本。

我正在尝试上述问题的最佳解决方案: Adding Regression Line Equation and R2 on graph

df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)

# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
lm_eqn <- function(df){
  m <- lm(y ~ x, df);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
                   list(a = format(coef(m)[1], digits = 2),
                        b = format(coef(m)[2], digits = 2),
                        r2 = format(summary(m)$r.squared, digits = 3)))
  as.character(as.expression(eq));
}

p <- ggplot(data = df, aes(x = x, y = y, label=y))+
  geom_smooth(method="lm", se=FALSE)+
  geom_point()

ymax <- max(df$y)* 0.95
xmean <- mean(df$x)

p1 <- p + geom_text(x = xmean, y = ymax, label = lm_eqn(df), parse = TRUE)
p1

ggplot

任何帮助,我们将不胜感激!

干杯

0 个答案:

没有答案