我制作了一個 GLM,并嘗試使用以下代碼使用 ggplot 繪制模型。我想我需要添加 type 引數,以便我的模型不只是產生水平的平線。但是,當我遇到此錯誤訊息時,我正在努力使用 type 引數來適應它;
Error in model.frame.default(Terms, newdata, na.action = na.action, xlev =
object$xlevels) :
object is not a matrix
這是我的資料集和用于獲取此問題的代碼,如果有人知道此問題的解決方法
我的資料(前 10 行);
aids
cases quarter date
1 2 1 83.00
2 6 2 83.25
3 10 3 83.50
4 8 4 83.75
5 12 1 84.00
6 9 2 84.25
7 28 3 84.50
8 28 4 84.75
9 36 1 85.00
10 32 2 85.25
我的代碼用于創建模型和繪圖
model3 = glm(cases ~ date,
data = aids,
family = poisson(link='log'))
#plotting the model (“link”, “response”, “terms”)
plot_predictions <- function(model, type = 'response') {
#make predictions
preds <- predict(model, df)
#plot
df %>%
ggplot(aes(date, cases))
geom_point()
geom_line(aes(date, preds), col = 'red')
ggtitle("Model 2 - Poisson GLM predicting cases")
theme(plot.title = element_text(hjust = 0.5, size = 12, face = 'bold'))
}
plot_predictions(model3, aids)
輸入輸出
dput(head(aids, 10))
structure(list(cases = c(2, 6, 10, 8, 12, 9, 28, 28, 36, 32),
quarter = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
2L), .Label = c("1", "2", "3", "4"), class = "factor"), date =
c(83,
83.25, 83.5, 83.75, 84, 84.25, 84.5, 84.75, 85, 85.25)),
row.names = c(NA,
10L), class = "data.frame")
uj5u.com熱心網友回復:
你在這里有點重新發明輪子。這可以使用 ggplot 自動完成geom_smooth
ggplot(aids, aes(date, cases))
geom_point()
geom_smooth(col = 'red', se= FALSE, method = glm,
method.args = list(family = poisson(link = 'log')))
ggtitle("Model 2 - Poisson GLM predicting cases")
theme(plot.title = element_text(hjust = 0.5, size = 12, face = 'bold'))

您甚至可以通過省略顯示標準錯誤se = FALSE:
ggplot(aids, aes(date, cases))
geom_segment(aes(xend = date, yend = 0), color = "deepskyblue4")
geom_point(size = 3)
geom_smooth(col = 'red3', fill = "red3", method = glm, alpha = 0.1,
method.args = list(family = poisson(link = 'log')))
ggtitle("Model 2 - Poisson GLM predicting cases")
theme_minimal(base_size = 16)
theme(plot.title = element_text(hjust = 0.5, face = 'bold'))

uj5u.com熱心網友回復:
這是將預測置于正確范圍內的一個:
library(tidyverse)
aids <- structure(list(cases = c(2, 6, 10, 8, 12, 9, 28, 28, 36, 32),
quarter = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L,
2L), .Label = c("1", "2", "3", "4"), class = "factor"), date =
c(83,
83.25, 83.5, 83.75, 84, 84.25, 84.5, 84.75, 85, 85.25)),
row.names = c(NA,
10L), class = "data.frame")
model3 = glm(cases ~ date,
data = aids,
family = poisson(link='log'))
plot_predictions <- function(model, df, type = 'response') {
require(tidyverse)
#make predictions
preds <- predict(model, df, type= type)
#plot
df %>%
ggplot(aes(date, cases))
geom_point()
geom_line(aes(date, preds), col = 'red')
ggtitle("Model 2 - Poisson GLM predicting cases")
theme(plot.title = element_text(hjust = 0.5, size = 12, face = 'bold'))
}
plot_predictions(model3, aids)

由
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483769.html
