简体   繁体   中英

Plotting a GAM (error in the plot output)

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;

在此处输入图像描述

Update of new error;

在此处输入图像描述

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

在此处输入图像描述

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

在此处输入图像描述

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