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.
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)
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)
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?