Home » How to Plot a Polynomial Regression Curve in R

How to Plot a Polynomial Regression Curve in R

by Tutor Aspire

Polynomial regression is a regression technique we use when the relationship between a predictor variable and a response variable is nonlinear.

This tutorial explains how to plot a polynomial regression curve in R.

Related: The 7 Most Common Types of Regression

Example: Plot Polynomial Regression Curve in R

The following code shows how to fit a polynomial regression model to a dataset and then plot the polynomial regression curve over the raw data in a scatterplot:

#define data
x #plot x vs. y
plot(x, y, pch=16, cex=1.5) 
 
#fit polynomial regression model
fit #use model to get predicted values
pred return=T)$ix

#add polynomial curve to plot
lines(x[ix], pred[ix], col='red', lwd=2)

plot polynomial regression curve in R

We can also add the fitted polynomial regression equation to the plot using the text() function:

#define data
x #plot x vs. y
plot(x, y, pch=16, cex=1.5) 
 
#fit polynomial regression model
fit #use model to get predicted values
pred return=T)$ix

#add polynomial curve to plot
lines(x[ix], pred[ix], col='red', lwd=2)

#get model coefficients
coeff #add fitted model equation to plot
text(9, 200 , paste("Model: ", coeff[1], " + ", coeff[2],
                    "*x", "+", coeff[3], "*x^2", "+", coeff[4], "*x^3"), cex=1.3)

Note that the cex argument controls the font size of the text. The default value is 1, so we chose to use a value of 1.3 to make the text easier to read.

Additional Resources

An Introduction to Polynomial Regression
How to Fit a Polynomial Curve in Excel
How to Perform Polynomial Regression in Python

You may also like