我已經設定了一個 GAM,但是當我繪制它時,我遇到了如下問題,有人知道如何解決這個問題嗎?下面使用的資料、模型和繪圖代碼;
資料片段:
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
模型和情節:
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')
目前繪制這個是不正確的;

更新新錯誤;

uj5u.com熱心網友回復:
假設您使用的是內置co2和mgcv庫:
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')

現在,如果您嘗試添加另一個術語,您的代碼將出錯:
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')

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/493121.html
上一篇:閃亮的按組繪制
