10.24 2011-09-26 00:52 采纳率: 0%
浏览 801
已采纳

在图上增加回归直线方程和 R2

I wonder how to add regression line equation and R^2 on the ggplot. My code is

library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
            geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
            geom_point()
p

Any help will be highly appreciated.

转载于:https://stackoverflow.com/questions/7549694/adding-regression-line-equation-and-r2-on-graph

  • 写回答

5条回答 默认 最新

  • 斗士狗 2011-09-26 01:20
    关注

    Here is one solution

    # GET EQUATION AND R-SQUARED AS STRING
    # SOURCE: http://goo.gl/K4yh
    
    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));                 
    }
    
    p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)
    

    EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups

    Output

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn