How to add RMSE, slope, intercept, r ^ 2 to the R-graph?

How can I add RMSE, slope, intercept and r ^ 2 to the graph using R? I attached a sample data script that looks like my real data set - unfortunately, I am in a wait state. Is there an easier way to add these statistics to the chart than to create an object from the equation and paste it into text() ? Ideally, I would like statistics to be displayed on a graph. How can i do this?

 ## 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) #Plot the data plot(mydata$x,mydata$y) abline(fit <- lm(y~x)) # Calculate RMSE model = sqrt(deviance(fit)/df.residual(fit)) # Add RMSE value to plot text(3,9,model) 
+7
source share
1 answer

Here is a version using basic graphics and ?plotmath to draw a graph 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) 

Then calculate the values ​​you want to display in the annotation. I prefer bquote() for this, where everything that is marked in .(foo) will be replaced with the value of the foo object. @Mnel's answer indicates that substitute() used in the comments to achieve the same, but using different means. Therefore, I create objects in the workspace for each value that you might want 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 create the equation using the constructs described in ?plotmath :

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

Once this is done, you can draw a plot and annotate it with your expression

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

What gives:

enter image description here

+16
source

All Articles