# 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.

### 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

lines(x[ix], pred[ix], col='red', lwd=2)
``` 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

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, " + ", coeff,
"*x", "+", coeff, "*x^2", "+", coeff, "*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.