简体   繁体   中英

ggplot2: Transparent legend background when stat_smooth is used

I have two plots. One with smoothed lines:

library(splines)
library(ggplot2)

ggplot(mtcars, aes(hp, qsec)) + stat_smooth(aes(group = cyl,
       colour = factor(cyl)),
       method = "glm",
       formula = y ~ ns(x, 1),
       level = 1e-9,
       size = I(1)) +
  theme(panel.background=element_rect(fill="transparent",colour=NA),
        plot.background=element_rect(fill="transparent",colour=NA),
        legend.key = element_rect(fill = "transparent", colour = "transparent"))

and one without:

ggplot(mtcars, aes(hp, qsec)) +
  geom_point(aes(group = cyl, colour = factor(cyl))) +
  theme(panel.background=element_rect(fill="transparent",colour=NA),
        plot.background=element_rect(fill="transparent",colour=NA),
        legend.key = element_rect(fill = "transparent", colour = "transparent"))

How can I get a white or transparent legend background in the first plot? And why do the same theme-commands do the job in the second plot?

It seems like the grey background is coming from stat_smooth() , as explained here . Adding se=FALSE , which deactivates the confidence intervals, seems to fix it:

ggplot(mtcars, aes(hp, qsec)) + stat_smooth(aes(group = cyl,
   colour = factor(cyl)),
   method = "glm",
   formula = y ~ ns(x, 1),
   level = 1e-9,
   size = I(1), 
   se = FALSE) +
   theme(panel.background=element_rect(fill="transparent",colour=NA),
      plot.background=element_rect(fill="transparent",colour=NA),
      legend.key = element_rect(fill = "transparent", colour = "transparent"))

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM