How to add RMSE, slope, intercept, r^2 to R plot?

后端 未结 1 2000
执念已碎
执念已碎 2020-12-13 07:47

How can I add RMSE, slope, intercept and r^2 to a plot using R? I have attached a script with sample data, which is a similar format to my real dataset--unfortunately, I am

相关标签:
1条回答
  • 2020-12-13 08:36

    Here is a version using base graphics and ?plotmath to draw the plot and annotate it

    ## Generate Sample Data
    x = c(2,4,6,8,9,4,5,7,8,9,10)
    y = c(4,7,6,5,8,9,5,6,7,9,10)
    
    ## Create a dataframe to resemble existing data
    mydata = data.frame(x,y)
    
    ## fit model
    fit <- lm(y~x, data = mydata)
    

    Next calculate the values you want to appear in the annotation. I prefer bquote() for this, where anything marked-up in .(foo) will be replaced by the value of the object foo. The Answer @mnel points you to in the comments uses substitute() to achieve the same thing but via different means. So I create objects in the workspace for each value you might wish to display in the annotation:

    ## Calculate RMSE and other values
    rmse <- round(sqrt(mean(resid(fit)^2)), 2)
    coefs <- coef(fit)
    b0 <- round(coefs[1], 2)
    b1 <- round(coefs[2],2)
    r2 <- round(summary(fit)$r.squared, 2)
    

    Now build up the equation using constructs described in ?plotmath:

    eqn <- bquote(italic(y) == .(b0) + .(b1)*italic(x) * "," ~~ 
                      r^2 == .(r2) * "," ~~ RMSE == .(rmse))
    

    Once that is done you can draw the plot and annotate it with your expression

    ## Plot the data
    plot(y ~ x, data = mydata)
    abline(fit)
    text(2, 10, eqn, pos = 4)
    

    Which gives:

    enter image description here

    0 讨论(0)
提交回复
热议问题