繁体   English   中英

在 ggplot2 中,使用现有 CI 变量指定 geom_smooth(或任何趋势线)周围的置信区间 (95% CI)

[英]In ggplot2, specify a confidence interval (95% CI) around geom_smooth (or any trend line) using existing CI variables

背景:

我有一个df随着时间的推移跟踪某人的weight (我发誓不是我的):

df <- data.frame(weight = c(156.8, 170,  185,   199.0, 203,  208), 
                lower95 = c(151.2, 165,  181.6, 194.5, 202,  206.4), 
                upper95 = c(162.8, 175,  187.9, 203.7, 204,  211.9),
                year =    c(2010,  2014, 2017,  2019,  2020, 2021)) 

我正在尝试在 R4DS 中制作一个像 Hadley 一样的简单geom_smooth ,如下所示:

data(mpg)
ggplot(data = mpg) + 
  geom_smooth(mapping = aes(x = displ, y = hwy))

我喜欢这个,因为它在主要趋势周围有一个阴影区域,代表 95% 的置信区间。 (我不确定这个 MPG 示例是如何从 MPG 数据中提取 CI 的——我没有看到 SE 变量——但这对于这个问题来说基本上是题外话。如果有人有一个好的答案,lmk。) .

问题:

正如您在我的数据集中看到的,我有 2 列, lower95upper95 ,它们包含每个观察的 CI。 我怎样才能将它们用作geom_smooth的阴影区域? 或者,如果不是geom_smooth ,那么任何趋势线?

我试过的:

我正在摆弄geom_linegeom_ribbon类的东西,但只会出现错误:

ggplot(data = df) +
  geom_line(data = df$weight) +
  geom_ribbon(data = df, aes(ymin = df$lower95, ymax = df$upper95))

您的最后一次尝试非常接近,但您从未指定xy 您也不应该在aes()中使用data$column ,它只需要不带引号的列名,并且您应该首先放置功能区,以便该行位于顶部。 而且您不需要继续指定data = df ,除非您在不同的层中使用不同的数据框。 给这个 go:

ggplot(data = df, aes(x = year, y = weight) +
  geom_ribbon(aes(ymin = lower95, ymax = upper95)) +
  geom_line()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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