简体   繁体   中英

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

I have a model from which i have predicted data but i have an aesthetics error on the geom_ribbon() argument of my plot when i try to add my confidence intervals. I think its something to do with the length of my CIs dataframe but not sure what changes i need to make, so if anyone if good with this sort of thing that would be great. The error reads;

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

All of my code used is here with a piece of my data at the end;

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')

data

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

You need inherit.aes = FALSE in geom_ribbon , since your ribbon data frame does not contain a co2 column

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')

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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