How to add exponential regression lines in R

We will see how to perform exponential regressions and how to plot these curved regression lines in base R and ggplot2, using the lines and geom_line functions, respectively. Please read my article about adding curved lines in base R and ggplot2 if you are interested in the different plotting options.

Scatterplots with exponential regression lines produced in base R (top) and ggplot2 (bottom)

Load the dataset

data("iris")

Variables assignment

dataset = iris
x_column = "Sepal.Length"
y_column = "Petal.Length"

Exponential regression

lm_results = lm(log(dataset[, y_column]) ~ dataset[, x_column])

Extract the exponential regression coefficients

intercept = coef(lm_results)[[1]]
slope = coef(lm_results)[[2]]

Compute the fitted values

dataset = dataset[order(dataset[, x_column]),]
dataset[, "exp"] = exp(slope * dataset[, x_column] + intercept)

Line color

acol = palette()[4]

Add an exponential regression line in base R

plot(dataset[, x_column], dataset[, y_column], pch = 18,
     xlab = x_column, ylab = y_column)
lines(dataset[, x_column], dataset[, "exp"], col = acol, lwd = 3)
Scatterplot with exponential regression line produced in base R

Add a exponential regression line in ggplot2

library(ggplot2)

ggplot(dataset, aes_string(x = x_column, y = y_column)) +
  geom_point(shape = 18)+
  geom_line(data = data.frame(x = dataset[, x_column], y = dataset[, "exp"]),
            aes(x = x, y = y), col = acol, lwd = 1)
Scatterplot with exponential regression line produced in ggplot2

Conclusion

In conclusion, it is possible to perform an exponential regression using the lm function and to plot the resulting line using base R graphics as well as the ggplot2 package.

Related posts

2 Comments

  1. Lidia

    This was extremely helpful!!!!! I have been dealing with it for days!! Thank you so much!!!

    • I’m glad it helped you! Thank you for your feedback, this is the first comment on my blog and it means a lot to me!

Leave a Reply