【问题标题】:How to add a line of best fit, equation, R^2, and p-value to a plot in R?如何在 R 中的绘图中添加一条最佳拟合线、方程、R^2 和 p 值?
【发布时间】:2020-03-30 01:46:04
【问题描述】:

我有 df1:

   Stabr  PCTPOVALL_2018 FIPS score1 score2    score3
3     AL  13.8          1001    26      3         10
4     AL  9.8           1003    20      1         5
7     AL  13.2          1009    21      6         7
8     AL  42.5          1011    60      5         10
9     AL  24.5          1013    65      3         10
10    AL  19.5          1015    42      2         8

我想针对score1 绘制df1$PCTPOVALL_2018。我还想进行线性回归,看看这些变量之间是否存在显着关联。然后,我想将 p 值、R^2 和最佳拟合线绘制到该图上。我已经包含了我在油漆中制作的图像以供参考。我知道从plot(df1$PCTPOVALL_2018,df1$score1,xlab="Pov",ylab="Score",main"Score vs Pov")开始

如何添加这些组件?我需要使用ggplot吗?

【问题讨论】:

    标签: r dataframe ggplot2 graph


    【解决方案1】:

    您可以使用abline根据调整后的线性模型的斜率和截距绘制直线,并使用text将附加信息添加到绘图中(使用paste将所有信息转换为字符串)。

    #Save summary of the linear model
    sum_lm<-summary(lm(score1~PCTPOVALL_2018, data = df1))
    
    #Get coefficients
    coef_lm<-sum_lm$coefficients
    
    #Plot
    plot(df1$PCTPOVALL_2018,
         df1$score1,
         xlab="Pov",
         ylab="Score",
         main= "Score vs Pov")
    
    #Set the abline as the coefficients obtained by your linear model
    abline(a = coef_lm[1,1], 
           b = coef_lm[2,1], 
           col = "lightblue",
           lwd = 2)
    
    #Add text to the plot in the x and y position (you might need to adjust these values according to your data)
    #and add as labels a string that pastes all the info you wish to include. \n is interpreted as a line break. 
    text(x = max(df1$PCTPOVALL_2018)-20, 
         y = min(df1$score1)+10, 
         labels = paste0("R^2 = ",
                         #Round r.squared to 2 decimals
                         round(sum_lm$r.squared,2),
                         "\np-value = ",
                         #Round p.value of slope to 2 decimals
                         round(coef_lm[2,4],2),
                         "\ny = ", 
                         #Round slope coefficient to 2 decimals
                         round(coef_lm[2,1],1),
                         "x + ", 
                         #Round intercept coefficient to 2 decimals
                         round(coef_lm[1,1],2)),
         pos = 4)
    

    这是包含您的数据的结果图。

    【讨论】:

    • 这太好了,有什么方法可以比位置 1、2、3 或 4 更具体地放置文本?
    • 是啊,其实text函数里面的xy是设置你要绘制文字的坐标,而pos只是根据指定坐标。例如,pos = 4 将文本绘制到这些坐标的右侧。
    • 你可以在plot函数中设置pchcol参数来改变数据点的默认颜色和形状。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2020-02-26
    • 1970-01-01
    • 2011-09-13
    相关资源
    最近更新 更多