【问题标题】:How to add linear model results (adj-r squared, slope and p-value) onto regression plot in r如何将线性模型结果(adj-r 平方、斜率和 p 值)添加到 r 中的回归图上
【发布时间】:2018-05-29 02:34:14
【问题描述】:

您好,我创建了一个线性模型和一个回归图 - 但是,我希望将模型结果显示在图本身上 - 如下图所示:

如何在图上显示关键结果?以下是我的情节代码:

library(ggplot2)
ggplot(HP_crime15, aes (x = as.numeric(HP_crime15$Theft15), y = 
as.numeric(HP_crime15$X2015))) + geom_point(shape=1) + 
geom_smooth(method=lm) + xlab ("Recorded number of Thefts") + 
ylab("House prices (£)") + ggtitle("Title") 

【问题讨论】:

    标签: r ggplot2 linear-regression coefficients


    【解决方案1】:

    理想的好问题是那些通过提供reproducible example 提出问题的问题。无论如何,我已经分两步解决了这个问题;

    第一步:确定线性回归模型;

    fit1 <- lm(Sepal.Length ~ Petal.Width, data = iris)
    

    第 2 步:绘制模型;

    library (ggplot2)
    ggplot(fit1$model, aes_string(x = names(fit1$model)[2], y = names(fit1$model)[1])) + 
      geom_point() +
      stat_smooth(method = "lm", col = "red") +
      labs(title = paste("Adj R2 = ",signif(summary(fit1)$adj.r.squared, 5),
                         "Intercept =",signif(fit1$coef[[1]],5 ),
                         " Slope =",signif(fit1$coef[[2]], 5),
                         " P =",signif(summary(fit1)$coef[2,4], 5)))
    

    【讨论】:

      【解决方案2】:

      这是另一种选择:您可以在绘图中添加标签,而不是在标题中添加统计信息:

      library (ggplot2)
      
      fit1 <- lm(Sepal.Length ~ Petal.Width, data = iris)   
      ggplot(fit1$model, aes_string(x = names(fit1$model)[2], y = names(fit1$model)[1])) + 
        geom_point() +
        stat_smooth(method = "lm", col = "red") +
        geom_label(aes(x = 0, y = 7.5), hjust = 0, 
                   label = paste("Adj R2 = ",signif(summary(fit1)$adj.r.squared, 5),
                                                     "\nIntercept =",signif(fit1$coef[[1]],5 ),
                                                     " \nSlope =",signif(fit1$coef[[2]], 5),
                                                     " \nP =",signif(summary(fit1)$coef[2,4], 5)))
      

      【讨论】:

        猜你喜欢
        • 2011-08-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-10
        • 1970-01-01
        • 2016-08-01
        • 2013-02-17
        相关资源
        最近更新 更多