I want to enclose the green loess line in the legend. I tried with this solution but I don't know how to set the linetype to the loess line (the first stat_smooth()). How would I do that? It should appear just to the right of the existing legend as: ----- loess.
library(ggplot2)
ggplot(mtcars, aes(wt, mpg, color=as.factor(vs), group=as.factor(vs))) +
stat_smooth(method="loess", se=FALSE, color="green",
lty=2, show.legend=TRUE,
aes(group=as.factor(vs))) +
stat_smooth(method="lm", formula=y ~ poly(x, 2, raw=TRUE),
se=FALSE, show.legend=TRUE)+
theme_minimal()+
# scale_linetype_manual("foo", values="green") + # won't work
# guides(linetype=guide_legend(override.aes=list(color="black"))) + # won't work either
guides(color = guide_legend(direction = "horizontal")) +
theme(legend.position = c(0, 1),
legend.justification = c("left", "top"),
legend.box.just = "right")

You can introduce an empty factor and tune it to look like the loess plot.
library(ggplot2)
library(tidyverse)
mtcars2 <- mtcars %>%
mutate(vs2 = factor(vs, levels = c("0", "1", "dotted")
, labels = c("0", "1", "dotted")))
ggplot(mtcars2, aes(wt, mpg, color=vs2, linetype=vs2)) +
stat_smooth(method="loess", se=FALSE, color="green",
lty=2, show.legend=TRUE,
aes(group=vs2)) +
stat_smooth(method="lm", formula=y ~ poly(x, 2, raw=TRUE),
se=FALSE, show.legend=TRUE)+
theme_minimal() +
scale_color_manual(values = c("red", "blue", "green"), drop = FALSE) +
scale_linetype_manual(values = c(1, 1, 2), drop = FALSE)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With