# R Language Plotting The Regression (base)

## Example

Continuing on the `mtcars` example, here is a simple way to produce a plot of your linear regression that is potentially suitable for publication.

First fit the linear model and

``````fit <- lm(mpg ~ wt, data = mtcars)
``````

Then plot the two variables of interest and add the regression line within the definition domain:

``````plot(mtcars\$wt,mtcars\$mpg,pch=18, xlab = 'wt',ylab = 'mpg')
lines(c(min(mtcars\$wt),max(mtcars\$wt)),
as.numeric(predict(fit, data.frame(wt=c(min(mtcars\$wt),max(mtcars\$wt))))))
``````

Almost there! The last step is to add to the plot, the regression equation, the rsquare as well as the correlation coefficient. This is done using the `vector` function:

``````rp = vector('expression',3)
rp[1] = substitute(expression(italic(y) == MYOTHERVALUE3 + MYOTHERVALUE4 %*% x),
list(MYOTHERVALUE3 = format(fit\$coefficients[1], digits = 2),
MYOTHERVALUE4 = format(fit\$coefficients[2], digits = 2)))[2]
rp[2] = substitute(expression(italic(R)^2 == MYVALUE),
list(MYVALUE = format(summary(fit)\$adj.r.squared,dig=3)))[2]
rp[3] = substitute(expression(Pearson-R == MYOTHERVALUE2),
list(MYOTHERVALUE2 = format(cor(mtcars\$wt,mtcars\$mpg), digits = 2)))[2]

legend("topright", legend = rp, bty = 'n')
``````

Note that you can add any other parameter such as the RMSE by adapting the vector function. Imagine you want a legend with 10 elements. The vector definition would be the following:

``````rp = vector('expression',10)
``````

and you will need to defined `r[1]`.... to `r[10]`

Here is the output: