Cannot remove grey area behind legend symbol when using smooth

笑着哭i 提交于 2020-05-09 05:49:04

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/33779219/cannot-remove-grey-area-behind-legend-symbol-when-using-smooth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!