{ggplot} geom_smooth 回归图中的置信区间仅出现在回归线下方

Confidence interval in {ggplot} geom_smooth regression plot appears only below regression line

我在互联网上到处搜索,但找不到问题的答案。我用 ggplot 绘制了一条带有置信区间的平滑回归线,但置信区域并未显示为回归线周围的带,而是仅显示在回归线下方。 这是图形错误还是我错过了正确的数学解释?

我使用了以下代码:

library(dplyr); library(ggplot2)

fig <-
  df %>%
  mutate(
    Legend = case_when(
      ind == "currentLifetimeRisk" ~ "Lifetime risk",
      ind == "currentTenYearRisk" ~ "Ten year risk"
    )
  ) %>%
  ggplot(aes(x = age_measurements,
             y = values,
             fill=Legend)) +
  geom_smooth(
    aes(ymin = 0,
        ymax = ..y..,),
    alpha = 0.8,
    formula = y ~ s(x, k = 9, bs="cs"),
    color= "black", # kleur van de lijn
    stat = "smooth",
    method = "gam",
    se = TRUE
  ) +
  scale_y_continuous(breaks = seq(0, 100, 25),
                     limits = c(0, 100), expand = c(0,0)) +
  scale_x_continuous(breaks = seq(30, max(fig2_long$age_measurements), 10), expand = c(0,0)) +
  theme(
    axis.text =element_text(family = "sans", size=18,colour = "black"),
    axis.title = element_text(size=18),
    axis.line.x = element_line(size=0.5, linetype="solid", colour="black"),
    axis.line.y = element_line(size=0.5, linetype="solid", colour="black"),
    panel.grid.major = element_line(colour = "lightgrey"),
    panel.background = element_blank(),
  ) +
  labs(
    x = "Age at risk estimation",
    y = "Risk of recurrent events (%)",
  )

我希望将 95% 置信区间视为回归线周围的一条带,而不仅仅是下方。非常感谢任何帮助。

aes(ymax=..y..) 的使用强制置信区间的顶部等于由 geom_smooth 计算的回归线的拟合 y 值。如果删除 aes(ymin = 0, ymax = ..y..),将绘制正确的置信区间。

..y....ymax....ymin.. 是由 geom_smooth 内部计算的值,用于绘制回归线和置信区间。设置 ymax=..y.. 强制 geom_smooth 使用 ..y..(回归的拟合 y 值)而不是 ..ymax..(95% 置信区间的计算顶部)作为顶部图中的 95% 置信区间,导致您看到的问题。 (我实际上不确定为什么 ymin=0 不强制 95% 置信区间的底部为零。)

删除 aes 映射(geom_smooth 不需要)会生成预期的置信区间绘图。下面的示例重现了您遇到的问题:

library(tidyverse)
library(patchwork)

p1 = mtcars %>% 
  ggplot(aes(mpg, hp, fill=factor(vs))) +
  geom_smooth(
    aes(ymin=0, ymax = ..y..,),
    alpha = 0.8,
    formula = y ~ s(x, k=9, bs="cs"),
    color= "black", # kleur van de lijn
    stat = "smooth",
    method = "gam",
    se = TRUE
  ) 

p2 = mtcars %>% 
  ggplot(aes(mpg, hp, fill=factor(vs))) +
  geom_smooth(
    alpha = 0.8,
    formula = y ~ s(x, k=9, bs="cs"),
    color= "black", # kleur van de lijn
    stat = "smooth",
    method = "gam",
    se = TRUE
  ) 

p1 + p2 

reprex package (v2.0.1)

于 2022-03-23 创建