Why can't I change the background color of a ggplot legend box to white? (Other colors work fine)

Viewed 621

I'm trying to recolor the legend of my ggplot object by adding theme(legend.key = element_rect(fill = "white")), but the legend remains gray. Oddly, this code works when I choose a colour other than "white".

Here is a small example with some dummy data:

## Dummy data
response <- rnorm(60, 50, 4)
year <- rep(c(1:10), 6)
treatment <- c(rep("A",30), rep("B", 30))
group <- c(rep(1, 20), rep(2, 20), rep(3, 20))
mydata <- data.frame(response, year, treatment, group)


library(ggplot2)

plot <- ggplot(mydata, aes(
       x = year,
       y = response,
       linetype = treatment,
       color = as.factor(group)
   )) +  geom_smooth()

## Specifying 'white' fill
plot + theme(legend.key = element_rect(fill = "white"))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

## Specifying 'blue' fill
plot + theme(legend.key = element_rect(fill = "blue"))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2021-01-26 by the reprex package (v0.3.0)

I've tried a few things with guide_legend() but I can't seem to crack it.

How can I turn the legend box white?


1 Answers

Besides setting the fill for the legend.key you have to set the fill color of the key_glyphs to white or NA via e.g. guide_legend. The reason is that the grey fill color in the legend keys reflects the fill color of the standard error ribbons drawn by geom_smooth:

response <- rnorm(60, 50, 4)
year <- rep(c(1:10), 6)
treatment <- c(rep("A",30), rep("B", 30))
group <- c(rep(1, 20), rep(2, 20), rep(3, 20))
mydata <- data.frame(response, year, treatment, group)

library(ggplot2)
ggplot(mydata, aes(
  x = year,
  y = response,
  linetype = treatment,
  color = as.factor(group)
)) +  
  geom_smooth() +
  guides(color = guide_legend(override.aes = list(fill = NA)),
         linetype = guide_legend(override.aes = list(fill = NA))) +
  theme(legend.key = element_rect(fill = "white"))
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Related