How to add curved lines in R

To add curved lines to plots in base R, we need the lines function. And to do it in ggplot2, we need the geom_line function. In the example below, we will use the local polynomial regression line computed with the loess function as an example of curved line.

Scatter plots with curved line (from loess output) produced with base R above and ggplot2 below

Load the ggplot2 package

library(ggplot2)

Load the dataset

data("iris")

Variables assignment

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

Local polynominal regression line

dataset = dataset[order(dataset[, x_column]),]
dataset[, "loess"] = loess(dataset[, y_column] ~ dataset[, x_column])$fitted

Colors

lcol = palette()[4]

Add curved lines in base R

plot(dataset[, x_column], dataset[, y_column], pch = 18,
     xlab = x_column, ylab = y_column)
lines(dataset[, x_column], dataset[, "loess"], col = lcol, lwd = 3)
Scatter plot with curved line (from loess output) produced with base R

Add curved lines in 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[, "loess"]),
            aes(x = x, y = y), col = lcol, lwd = 1)
Scatter plot with curved line (from loess output) produced with ggplot2

Conclusion

In conclusion, it is a bit easier to add the curved line in base R rather than in ggplot2. But in the end, both look exactly the same. Do you prefer base R or ggplot2?

Related posts

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply