geom_smooth 的置信带怎样跟随分组变色?

拟合线已经按组变色,为什么置信带还是灰色?

在 geom_smooth() 中将 fill 和 colour 映射到同一个分组,使用一致的配色标度,再用 alpha = 0.22 显示重叠的置信带。

本文目录

发布与实测日期:2026 年 11 月 18 日。

colour 控制拟合线,fill 控制带状区域。给平滑层加入 aes(fill = group),再让 scale_fill_manual() 与 scale_colour_manual() 使用同一份有名称的配色。本例 A 为蓝色,B 为橙色。透明度0.22是本例的显示选择,需按实际图形检查。平滑层官方文档。

修改前后,图中具体变了什么?

我先看阴影,再看中间的拟合线。这样一眼就能分清,这次改到的是带子的填色,还是线条的颜色。

修改前:两组拟合线颜色不同,但置信带均为灰色。
查看原尺寸图片
修改前:两条置信带都使用灰色。两版共用84个自制模拟观测,输入和响应均为任意单位。本文使用模拟演示数据
修改后:蓝色与橙色置信带分别匹配两组拟合线。
查看原尺寸图片
修改后:只增加填充映射及相应标度。A仍为实线和圆点,B仍为虚线和三角点。重叠处同时包含两种半透明填充。窄屏可在图内横向滚动。

怎样让线、置信带和图例保持一致?

使用有名称的配色,例如 c(A = "#0072B2", B = "#D55E00"),并统一颜色标度与填充标度的标题、类别顺序和标签。本例还用线型、点形区分组别,阅读时可结合这些线索。手动标度文档。

改置信带颜色会改变拟合结果吗?

本例不会,因为 colour 已经按两组分别拟合,新增的 fill 指向同一个因子。脚本核对了两版共160个计算位置的拟合值、区间下界与上界,均保持相同,并用 predict.lm() 独立复核区间。

这里使用 method = "lm"、se = TRUE、level = 0.95,显示均值响应的逐点95%置信区间。拟合值与区间边界保持原样;需要检验组间差异时,另行采用合适的分析方法。

怎样运行完整例子并取得结果文件?

把R脚本放在空的输出文件夹中,准备好ggplot2,在该目录运行 Rscript --vanilla example.R。脚本自行创建模拟数据,已在R 4.5.3与ggplot2 4.0.4运行。PNG实测1200 × 900像素、约300 PPI;PDF页面为101.6 × 76.2 mm。这些尺寸仅供示例。PDF使用默认设备导出,未据此确认字体嵌入合规。

下面是本文用到的代码、数据和结果文件。你可以下载代码跟着操作,也可以打开结果文件,对照自己运行后的结果。

  • example.R可以在电脑上运行的完整示例代码。
  • synthetic.csv本例使用的输入数据,可作为表格打开。
  • before.png修改前的图,用来比较。
  • after.png按本文设置生成的结果图。
  • after.pdfPDF 格式的结果图,方便查看和排版。

尺寸换算使用像素计算器,多图排列见既有导出教程。

# Original synthetic example, code and data: CC0-1.0.
library(ggplot2)
set.seed(20261118)
d <- expand.grid(x = seq(0, 10, by = 0.5), replicate = 1:2,
                 group = c("A", "B"))
d$group <- factor(d$group, levels = c("A", "B"))
d$y <- 3 + 0.45 * d$x + ifelse(d$group == "B", 0.8, 0) +
  rnorm(nrow(d), sd = 2)
write.csv(d, "synthetic.csv", row.names = FALSE)
palette <- c(A = "#0072B2", B = "#D55E00")
make_plot <- function(match_fill = FALSE) {
  p <- ggplot(d, aes(x, y, colour = group, linetype = group)) +
    geom_point(aes(shape = group), size = 1, alpha = 0.45) +
    scale_colour_manual(name = "Group", values = palette) +
    scale_linetype_manual(name = "Group", values = c(A = "solid", B = "dashed")) +
    scale_shape_manual(name = "Group", values = c(A = 16, B = 17)) +
    labs(x = "Input (arbitrary units)", y = "Response (arbitrary units)",
         caption = "Synthetic data; pointwise 95% mean-response intervals") +
    theme_classic(base_size = 9) +
    theme(legend.position = "top", plot.caption = element_text(size = 7),
          plot.margin = margin(6, 7, 6, 6))
  if (match_fill) {
    p <- p + geom_smooth(aes(fill = group), method = "lm", formula = y ~ x,
                         se = TRUE, level = 0.95, alpha = 0.22, linewidth = 0.65) +
      scale_fill_manual(name = "Group", values = palette)
  } else {
    p <- p + geom_smooth(method = "lm", formula = y ~ x,
                         se = TRUE, level = 0.95, alpha = 0.22, linewidth = 0.65)
  }
  p
}
before <- make_plot(FALSE)
after <- make_plot(TRUE)
# The second layer is the smoother; style edits must preserve its estimates.
b <- ggplot_build(before)$data[[2]]
a <- ggplot_build(after)$data[[2]]
stopifnot(isTRUE(all.equal(b[c("x", "y", "ymin", "ymax", "group")],
                           a[c("x", "y", "ymin", "ymax", "group")],
                           check.attributes = FALSE)),
          length(unique(b$fill)) == 1L, length(unique(a$fill)) == 2L,
          all(a$alpha == 0.22), nrow(d) == 84L)
# Independently verify ggplot's pointwise mean confidence intervals with predict.lm.
for (id in 1:2) {
  rows <- a[a$group == id, ]
  fit <- lm(y ~ x, data = d[d$group == levels(d$group)[id], ])
  ci <- predict(fit, data.frame(x = rows$x), interval = "confidence", level = .95)
  stopifnot(max(abs(rows$y - ci[, "fit"])) < 1e-9,
            max(abs(rows$ymin - ci[, "lwr"])) < 1e-9,
            max(abs(rows$ymax - ci[, "upr"])) < 1e-9)
}
ggsave("before.png", before, width = 1200, height = 900, units = "px", dpi = 300, bg = "white")
ggsave("after.png", after, width = 1200, height = 900, units = "px", dpi = 300, bg = "white")
ggsave("after.pdf", after, width = 101.6, height = 76.2, units = "mm", bg = "white")
write.csv(a[c("x", "y", "ymin", "ymax", "group", "colour", "fill", "alpha")],
          "computed-smooth.csv", row.names = FALSE)
capture.output(sessionInfo(), file = "session-info.txt")
cat("PASS: 84 synthetic observations; 2 group models; 160 evaluated rows; unchanged fits and bounds; independent predict.lm matches.\n")

问题和示例数据来自哪里?

选题来自 2026 年 9 月 12 日的 Reddit 问题。数据、代码和图形为本文自行设计。

Reddit · 2026-09-12

本文原创脚本、模拟数据及生成的 PNG/PDF 以 CC0-1.0 提供,允许商业复用。ggplot2 保留 MIT 许可,R 保留 GPL-2 或 GPL-3 许可;下载文件不包含这些包的软件代码。

CC0-1.0 · Credits