How to Plot a Polynomial Regression Curve in R


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 <- runif(50, 5, 15)
y <- 0.1*x^3 - 0.5 * x^2 - x + 5 + rnorm(length(x),0,10) 
 
#plot x vs. y
plot(x, y, pch=16, cex=1.5) 
 
#fit polynomial regression model
fit <- lm(y ~ x + I(x^2) + I(x^3))
 
#use model to get predicted values
pred <- predict(fit)
ix <- sort(x, index.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 <- runif(50, 5, 15)
y <- 0.1*x^3 - 0.5 * x^2 - x + 5 + rnorm(length(x),0,10) 
 
#plot x vs. y
plot(x, y, pch=16, cex=1.5) 
 
#fit polynomial regression model
fit <- lm(y ~ x + I(x^2) + I(x^3))
 
#use model to get predicted values
pred <- predict(fit)
ix <- sort(x, index.return=T)$ix

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

#get model coefficients
coeff <- round(fit$coefficients , 2)

#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

Leave a Reply

Your email address will not be published. Required fields are marked *