Remove grey from legend in ggplot2

2019-07-08 03:08发布

问题:

I would like to remove the grey (which is there because of the SE from geom_smooth) from the legend boxes. I would like to keep the SE in the actual plot though. So in the legend boxes, I just want the color of the lines, not the shadings. Here is an example:

library(ggplot2)

x <- rnorm(100)
y <- rnorm(100)
g_ <- sample(c("group1", "group2"), 100, replace = TRUE)

ggplot(data.frame(x, y, g_), aes(x = x, y = y, color = g_)) + geom_smooth()

回答1:

Here's a way. First, draw lines with confidence intervals, but no legend. Then, draw lines with no intervals and a legend, and finally, color the legend key white.

ggplot(data.frame(x, y, g_), aes(x = x, y = y, color = g_)) + 
  geom_smooth(show_guide=FALSE) +
  geom_smooth(fill=NA) +
  theme(legend.key = element_rect(fill = "white"))



标签: r ggplot2 legend