pir
pir

Reputation: 5923

Cannot remove grey area behind legend symbol when using smooth

I'm using ggplot2 with a GAM smooth to look at the relationship between two variables. When plotting I'd like to remove the grey area behind the symbol for the two types of variables. For that I would use theme(legend.key = element_blank()), but that doesn't seem to work when using a smooth.

Can anyone tell me how to remove the grey area behind the two black lines in the legend?

I have a MWE below.

library(ggplot2)

len <- 10000
x <- seq(0, len-1)
df <- as.data.frame(x)
df$y <- 1 - df$x*(1/len)
df$y <- df$y + rnorm(len,sd=0.1)
df$type <- 'method 1'
df$type[df$y>0.5] <- 'method 2'

p <- ggplot(df, aes(x=x, y=y)) + stat_smooth(aes(lty=type), col="black", method = "auto", size=1, se=TRUE)
p <- p + theme_classic()
p <- p + theme(legend.title=element_blank())
p <- p + theme(legend.key = element_blank()) # <--- this doesn't work?
p

enter image description here

Upvotes: 4

Views: 3260

Answers (1)

Heroka
Heroka

Reputation: 13149

Here is a very hacky workaround, based on the notion that if you map things to aestethics in ggplot, they appear in the legend. geom_smooth has a fill aesthetic which allows for different colourings of different groups if one so desires. If it's hard to fix that downstream, sometimes it's easier to keep those unwanted items out of the legend altogether. In your case, the color of the se appeared in the legend. As such, I've created two geom_smooths. One without a line color (but grouped by type) to create the plotted se's, and one with linetype mapped to aes but se set to false.

p <- ggplot(df, aes(x=x, y=y)) + 
  #first smooth; se only
  stat_smooth(aes(group=type),col=NA, method = "auto", size=1, se=TRUE)+
  #second smooth: line only
  stat_smooth(aes(lty=type),col="black", method = "auto", size=1, se=F) +
  theme_classic() +
  theme(
    legend.title = element_blank(),
    legend.key = element_rect(fill = NA, color = NA)) #thank you @alko989

enter image description here

Upvotes: 8

Related Questions