Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include loess line in ggplot2 legend?

Tags:

r

legend

ggplot2

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")

enter image description here

like image 874
jay.sf Avatar asked Dec 10 '25 06:12

jay.sf


1 Answers

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)

enter image description here

like image 168
YCR Avatar answered Dec 11 '25 20:12

YCR



Donate For Us

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