我創建了以下二項式 GLM 模型并希望使用 ggplot 對其進行繪制。我遇到的問題是如何將多個變數繪制為 x 和 y 軸。
notUsing, using 是使用年齡 教育 想要更多來預測的。由于有多個變數,我如何將這些作為引數添加到 ggplot 的 aes() 中?
這應該在下面更清楚。
創建的模型;
my_model = glm(cbind(notUsing, using) ~ age education wantsMore,
data = contraceptive2,
family = binomial(link = "logit"))
繪制模型;(希望這會讓我更容易看到我失敗的地方。我需要為我的資料重放 x 和 y,但由于它們包含多個變數,我不知道該怎么做)
#make predictions
my_model_preds = predict(my_model, contraceptive2, se.fit = TRUE, type = 'response')
#ggplot of the model
ggplot(contraceptive2, aes(x, y))
geom_point()
geom_line(aes(x, my_model_preds), col = 'blue')
如果需要,部分資料;
head(contraceptive2)
age education wantsMore notUsing using
1 <25 low yes 53 6
2 <25 low no 10 4
3 <25 high yes 200 52
4 <25 high no 50 10
5 25-29 low yes 60 14
6 25-29 low no 19 10
7 25-29 high yes 155 54
8 25-29 high no 65 27
9 30-39 low yes 112 33
10 30-39 low no 77 80
11 30-39 high yes 118 46
12 30-39 high no 68 78
13 40-49 low yes 35 6
14 40-49 low no 46 48
15 40-49 high yes 8 8
16 40-49 high no 12 31
uj5u.com熱心網友回復:
通過提供的資料,我們可以看到,因為您的兩個自變數是二元的,所以可以使用帶有刻面和顏色的誤差線繪制整個模型:
df <- with(contraceptive2,
expand.grid(age = unique(age), education = unique(education),
wantsMore = unique(wantsMore)))
fits <- predict(my_model, newdata = df, se.fit = TRUE)
# Get odds from modrl
df$prediction <- exp(fits$fit)
df$upper <- exp(fits$fit 1.96 * fits$se.fit)
df$lower <- exp(fits$fit - 1.96 * fits$se.fit)
# Convert odds to probabilities
df$prediction <- df$prediction / (1 df$prediction)
df$upper <- df$upper / (1 df$upper)
df$lower <- df$lower / (1 df$lower)
# Plot probabilities
ggplot(df, aes(age, prediction))
geom_errorbar(aes(ymin = lower, ymax = upper, colour = wantsMore),
width = 0.25, size = 1, position = position_dodge(width = 0.4))
geom_point(aes(fill = wantsMore), shape = 21, size = 3,
position = position_dodge(width = 0.4))
facet_grid(~education)
theme_light(base_size = 16)
scale_y_continuous(name = "Probability of not using", limits = c(0, 1),
labels = scales::percent)

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483760.html
上一篇:除形狀外具有不同顏色的線性回歸線
下一篇:線型中沒有重疊的條形圖
