By default, stat_smooth
inherits unspecified aesthetics from the original plot, in this case colour
. But colour
refers to vs
, which isn't a variable in the new dat
data frame, hence the error. All you need to do though, is tell it what the new grouping variable is, in this case, colour
. Note that I'm adding method="lm", se=FALSE
as well because there's just not enough data points here for the default smooth.
p <- ggplot(mtcars, aes(x=cyl, colour=factor(vs))) +
geom_line(stat = 'count')
dat <- layer_data(p)
p + stat_smooth(data = dat, aes(x, y, colour=colour),
method="lm", se=FALSE)
You'll notice, though, that the colors don't match, because the variables don't match. I suspect the cleanest way to deal with this will be to get the counts ahead of time in a new data frame and then to use that in the plotting.
library(tidyverse)
mtcars %>% mutate_at(vars(cyl, vs), factor) %>%
group_by(cyl, vs) %>% summarize(n=n()) %>%
ggplot() + aes(x=cyl, y=n, colour=vs, group=vs) +
geom_line() +
stat_smooth(method="lm", se=FALSE)