ggplot2:使用stat_smooth时的透明图例背景

时间:2015-10-22 23:24:20

标签: r plot ggplot2 smoothing

我有两个情节。一条线条平滑:

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"))

和一个没有:

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"))

如何在第一个图中获得白色或透明的图例背景? 为什么相同的主题命令在第二个绘图中完成工作?

1 个答案:

答案 0 :(得分:11)

灰色背景似乎来自stat_smooth(),正如here所解释的那样。添加se=FALSE会停用置信区间,似乎可以修复它:

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"))

enter image description here