Home > Net >  Plotting a GAM (error in the plot output)
Plotting a GAM (error in the plot output)

Time:06-17

I have set up a GAM but when i plot it i run into the issue as below, does anyone know how to fix this issue? Data, model and plot code used below;

data snipet:

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

model and plot:

carbonD_model = gam(co2 ~ s(timeStep, k = 4, bs = "cs"),
                    data = carbonD,
                    family = gaussian(link = "identity"))

#predictions
preds = predict(carbonD_model, type = 'terms', se.fit = TRUE)

#plotting the model
ggplot(carbonD, aes(timeStep, co2))  
  geom_point()  
  geom_line(aes(timeStep, preds$fit), col = 'red')

currently plot this which is incorrect;

enter image description here

CodePudding user response:

Assuming you're using the built-in co2 and mgcv library:

library(data.table)
library(mgcv)
library(ggplot2)

carbonD <- data.table(co2 = as.vector(co2), time = as.vector(time(co2)))
carbonD[, year := trunc(time)]
carbonD[, month := (time - year) * 12   1]
carbonD[, timeStep := .I]

carbonD_model = gam(co2 ~ s(timeStep, k = 4, bs = "cs"),
                    data = carbonD,
                    family = gaussian(link = "identity"))

#predictions
preds = predict(carbonD_model, type = 'response', se.fit = TRUE)

#plotting the model
ggplot(carbonD, aes(timeStep, co2))  
  geom_point()  
  geom_line(aes(timeStep, preds$fit), col = 'red')

enter image description here

Now if you tried to add another term, your code would error out with:

carbonD_model = gam(co2 ~ s(timeStep, k = 4, bs = "cs")   s(year, k = 3, bs = "cs"),
                    data = carbonD,
                    family = gaussian(link = "identity"))

#predictions
preds = predict(carbonD_model, type = 'terms', se.fit = TRUE)

#plotting the model
ggplot(carbonD, aes(timeStep, co2))  
  geom_point()  
  geom_line(aes(timeStep, preds$fit), col = 'red')

# Error: Aesthetics must be either length 1 or the same as the data (468): y

# but changing it to response
preds = predict(carbonD_model, type = 'response', se.fit = TRUE)

#plotting the model
ggplot(carbonD, aes(timeStep, co2))  
  geom_point()  
  geom_line(aes(timeStep, preds$fit), col = 'red')

enter image description here

  • Related