I am looking to plot smoothed lines of subsets of a dataset on top of an overall plot of the data.
For example in the image below, I would be looking to plot the green and blue datapoints on the right as a separate geom_smooth
line.
A reproducible example of the code would be as follows:
library(datasets)
library(ggplot2)
library(tidyr)
iris_subset <- subset(iris, Species == "virginica" | Species == "versicolor")
p <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species))
p <- p + geom_point()
p <- p + geom_smooth(method="loess", colour = "black")
p <- p + geom_smooth(aes(data = iris_subset, x = Sepal.Length, y = Sepal.Width), method="loess", colour = "red")
print(p)
When I attempt this however, it throws the error "Error: Aesthetics must be either length 1 or the same as the data"
This seems to imply that it doesn't like the inclusion of a subset of different length plotted on the same axis as the original, but after playing with it I've hit a wall.