Remove fill around legend key for geom_ribbon in ggplot2

Viewed 200

I want to remove the fill inside the legend that is created with geom_ribbon. Note that these answers do not solve this particular issue.

Minimal Working Example

library(ggplot2)
library(ggeffects)

fit <- lm(mpg ~ hp*disp, data= mtcars)

me <- ggeffect(fit,
               ci.lvl = .95,
               type = "fe",
               terms = c("hp", "disp"))

ggplot(data = me,
       mapping = aes(x = x, y = predicted, linetype = group)) +
  geom_line() +
  geom_ribbon(aes(ymin = conf.low,
                  ymax = conf.high),
              alpha = .5)

enter image description here

I want this plot, but I want the legend to look like this: enter image description here

1 Answers

Great question! A potential solution is to include show.legend = FALSE and also remove the legend key background using theme() (each of these actions won't 'work' on their own), e.g.

library(tidyverse)
# install.packages("ggeffects")
library(ggeffects)

fit <- lm(mpg ~ hp*disp, data= mtcars)

me <- ggeffect(fit,
               ci.lvl = .95,
               type = "fe",
               terms = c("hp", "disp"))

ggplot(data = me,
       mapping = aes(x = x, y = predicted, linetype = group)) +
  geom_line() +
  geom_ribbon(aes(ymin = conf.low,
                  ymax = conf.high),
              alpha = .5, show.legend = FALSE) +
  theme(legend.key = element_blank())

Created on 2021-08-24 by the reprex package (v2.0.0)

Does this answer translate to your actual data?

Related