在向ggplot添加带有可见标准误带的LOESS平滑线时,图例背景颜色出现问题

编程语言 2026-07-09

我喜欢 theme_bw(),并且尽量让图例尽可能不显眼(没有背景,没有矩形框)。只要我不显示loess平滑的SE带,一切都正常。很抱歉混用法语和英语,我尽量让这个可复现的示例尽可能接近我原始的项目。

简单数据集:

set.seed(123)
n <- 200
dcomb <- data.frame(
  DatHr  = seq(as.POSIXct("2024-01-01"), by = "hour", length.out = n),
  Radon  = c(rnorm(n/2, mean = 150, sd = 30),
             rnorm(n/2, mean = 100, sd = 20)),
  endroit = rep(c("A", "B"), each = n/2)
)

# This works well (no shading of SE band, background of legend as desired):
ggplot(dcomb, aes(x = DatHr, y = Radon, colour = endroit)) +
  theme_bw() +
  geom_line(alpha = 0.7) +
  geom_smooth(method = "loess", span = 0.2, se= FALSE) +
  theme(
    legend.position = "inside",
    legend.position.inside = c(0.8, 0.95),
    legend.justification.inside = c("center", "top"),
    legend.background = element_rect(fill = "white", colour = NA),
    legend.key = element_rect(fill = "white", colour = NA)
  )

# but the background of the legend become same as shading of SE band here:
ggplot(dcomb, aes(x = DatHr, y = Radon, colour = endroit)) +
  theme_bw() +
  geom_line(alpha = 0.7) +
  geom_smooth(method = "loess", span = 0.2, se= FALSE) +
  theme(
    legend.position = "inside",
    legend.position.inside = c(0.8, 0.95),
    legend.justification.inside = c("center", "top"),
    legend.background = element_rect(fill = "white", colour = NA),
    legend.key = element_rect(fill = "white", colour = NA)
  )

我真的不知道该怎么修复这个问题。

非常感谢您的帮助,

Denis

解决方案

我发现你有两处相同的代码都使用了 se = FALSE。问题出现在 se = TRUE 时。

se = TRUE 时,geom_smooth() 会添加置信带(带状区域),最终在图例中引入一个 fill 的美感。那种填充似乎覆盖了你图例的白色背景。

你可以通过使用 override.aes 将图例中的填充去掉来修复这个问题:

示例

ggplot(dcomb, aes(x = DatHr, y = Radon, colour = endroit)) +
  theme_bw() +
  geom_line(alpha = 0.7) +
  geom_smooth(method = "loess", span = 0.2, se = TRUE) +
  guides(
    colour = guide_legend(
      override.aes = list(fill = NA)
    )
  ) +
  theme(
    legend.position = "inside",
    legend.position.inside = c(0.8, 0.95),
    legend.justification.inside = c("center", "top"),
    legend.background = element_rect(fill = "white", colour = NA),
    legend.key = element_rect(fill = "white", colour = NA)
  )
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章