狐狸.fox 2011-09-26 00:52 采纳率: 0%
浏览 987
已采纳

在图上增加回归直线方程和 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条回答 默认 最新

  • derek5. 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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题