从 ggplot 置信区间中提取值

问题描述 投票:0回答:2

我能够根据我的数据使用 geom_smooth 和 R 中的 method = "lm" 绘制一条线。但是,我想知道如何从我的 ggplot 中轻松提取值。我对用于创建置信区间的值特别感兴趣。可重现的代码如下。谢谢!

app <- structure(list(Year = 2019:2014, NP_total = c(892L, 867L, 765L, 
635L, 572L, 554L)), row.names = c(NA, -6L), class = c("data.table", 
"data.frame"))

ggplot() + geom_smooth(data = app, mapping = aes(x = Year, y = NP_total), color = "black", method = "lm")


r ggplot2 line
2个回答
2
投票

由于您在 geom_smooth 中使用“lm”方法,因此您可以在 ggplot 之外使用相同的方法:

lm(NP_total~Year,app)

要提取置信区间,您可以使用相同的“lm”模型来使用用于制作模型的相同年份值来预测 NP_total 值。这是一句单行话。

smooth_values <- predict(lm(NP_total~Year,app), data = app$Year, se.fit = TRUE)

确保预测函数中有

se.fit = TRUE
以输出您正在寻找的置信区间。我希望这就是您正在寻找的。


0
投票

要获取绘制的实际数据,请保存为对象,然后访问数据层。

pl1 <- ggplot() + 
  geom_smooth(data = app, 
              aes(x = Year, y = NP_total), 
              color = "black", 
              method = "lm")
layer_data(pl1) %>% head() 
`geom_smooth()` using formula = 'y ~ x'
         x        y     ymin     ymax       se flipped_aes PANEL group colour   fill linewidth linetype weight alpha
1 2014.000 520.9524 448.7108 593.1939 26.01944       FALSE     1    -1  black grey60         1        1      1   0.4
2 2014.063 525.8439 454.8442 596.8436 25.57215       FALSE     1    -1  black grey60         1        1      1   0.4
3 2014.127 530.7354 460.9670 600.5038 25.12868       FALSE     1    -1  black grey60         1        1      1   0.4
4 2014.190 535.6269 467.0786 604.1752 24.68922       FALSE     1    -1  black grey60         1        1      1   0.4
5 2014.253 540.5184 473.1785 607.8583 24.25400       FALSE     1    -1  black grey60         1        1      1   0.4
6 2014.316 545.4099 479.2659 611.5538 23.82325       FALSE     1    -1  black grey60         1        1      1   0.4
© www.soinside.com 2019 - 2024. All rights reserved.