繁体   English   中英

置信区间不会绘制预测数据(绘图问题)

[英]Confidence intervals won't plot for predicted data (plotting problem)

我有一个模型,我从中预测了数据,但是当我尝试添加置信区间时,我的绘图的 geom_ribbon() 参数出现美学错误。 我认为这与我的 CI 数据框的长度有关,但不确定我需要进行哪些更改,所以如果有人对这种事情很好,那就太好了。 错误读取;

Aesthetics must be either length 1 or the same as the data (52): y Backtrace

我使用的所有代码都在这里,最后是我的一段数据;

carbonD_mod = gam(co2 ~ s(timeStep, k = 50, bs = "cs") + s(month, k = 12, bs = "cc"), 
                data = carbonD,
                family = gaussian(link = "identity"))

#creating a vector of year and month
ts = seq(469,520, length.out = 52) #the 52 weeks from 1998
mon = seq(1,12, length.out = 52)
#combine vectors into a df
newdata = data.frame(timeStep = ts, month = mon)

#creating our new predictions
new_preds = predict(carbonD_mod, newdata, type = 'response', se.fit = TRUE)
new_fit = new_preds$fit

#creating confidence intervals
preds_ci = predict(carbonD_mod, newdata, type = 'link', se.fit = TRUE)
lower_ci = preds_ci$fit - 1.96 * preds_ci$se.fit
upper_ci = preds_ci$fit + 1.96 * preds_ci$se.fit

#combining confidence intervals into a df
predframe_ci = data.frame(lwr = lower_ci, upr = upper_ci, timeStep = ts, cases = mon)

#plotting our 1998 model predictions
ggplot(newdata, aes(timeStep, co2)) + 
  geom_ribbon(data = predframe_ci, aes(ymin = lwr, ymax = upr), fill = 'grey') +
  geom_line(aes(timeStep, new_fit), col = 'red')

数据

carbonD
       co2 month year timeStep
1   315.42     1 1959        1
2   316.31     2 1959        2
3   316.50     3 1959        3
4   317.56     4 1959        4
5   318.13     5 1959        5
6   318.00     6 1959        6
7   316.39     7 1959        7
8   314.65     8 1959        8
9   313.68     9 1959        9
10  313.18    10 1959       10
11  314.66    11 1959       11
12  315.43    12 1959       12
13  316.27     1 1960       13
14  316.81     2 1960       14
15  317.42     3 1960       15
16  318.87     4 1960       16
17  319.87     5 1960       17
18  319.43     6 1960       18
19  318.01     7 1960       19
20  315.74     8 1960       20

您需要在geom_ribbon中继承inherit.aes = FALSE ,因为您的功能区数据框不包含co2

ggplot(newdata, aes(timeStep, co2)) + 
  geom_ribbon(data = predframe_ci, 
              aes(x = timeStep, ymin = lwr, ymax = upr), fill = 'grey',
              inherit.aes = FALSE, alpha = 0.5) +
  geom_line(aes(timeStep, new_fit), col = 'red')

在此处输入图像描述

暂无
暂无

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

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