I have the same question that was asked here 3 years ago:
The accepted answer doesn't seem to work (that is, changing the values in the span list don't make any difference to the plot)
# doesn't seem to work:
mtcars %>%
ggplot(aes(x = wt, y = mpg, color = factor(am))) +
geom_point() +
stat_smooth(geom = "smooth",
method = "loess", formula = y ~ x,
method.args = list(span = c(0.2, 0.8)))
# works but is clunky:
ggplot() +
geom_point(data = mtcars,
aes(x = wt, y = mpg, color = factor(am))) +
geom_smooth(data = mtcars |>
filter(am ==1),
aes(x = wt, y = mpg, color = factor(am)),
method = "loess", span = 0.2,
show.legend = FALSE) +
geom_smooth(data = mtcars |>
filter(am == 0),
aes(x = wt, y = mpg, color = factor(am)),
method = "loess", span = 0.8)
I have 2 related questions.
- Is there a more streamlined way to use different spans for different groups of data other than looping through all the grouping levels?
- Is there a good way to get the legend to show smoothing lines on only the data that has the smoothing line? Here's what I mean by that. Let's say we want to do this:
ggplot(data = mtcars,
aes(x = wt, y = mpg, color = factor(am))) +
geom_point() +
geom_smooth(data = mtcars |>
filter(am ==1),
aes(x = wt, y = mpg,
color = factor(am), group = factor(am)),
method = "loess", span = 0.5)
I think I could hack a custom legend together, but if there's some way to get it to work in a more legitimate way, that would be great to learn.