[英]How can I add a layer showing the distribution on a conditional variable in a probability plot in R studio?
我正在擬合以下回歸: model <- glm(DV ~ conditions + predictor + conditions*predictor, family = binomial(link = "probit"), data = d)
。
我使用'sjPlot'(和'ggplot2')制作以下plot:
library("ggplot2")
library("sjPlot")
plot_model(model, type = "pred", terms = c("predictor", "conditions")) +
xlab("Xlab") +
ylab("Ylab") +
theme_minimal() +
ggtitle("Title")>
但是我不知道如何添加一個顯示條件變量分布的圖層,就像我可以通過使用“interplot”設置“hist = TRUE”輕松做到的那樣:
library("interplot")
interplot(model, var1 = "conditions", var2 = "predictor", hist = TRUE) +
xlab("Xlab") +
ylab("Ylab") +
theme_minimal() +
ggtitle("Title")
我也只使用 ggplot 嘗試了一堆圖層,但沒有成功
ggplot(d, aes(x=predictor, y=DV, color=conditions))+
geom_smooth(method = "glm") +
xlab("Xlab") +
ylab("Ylab") +
theme_minimal() +
ggtitle("Title")
.
我願意接受任何建議!
我顯然不得不嘗試重新創建您的數據以使其正常工作,因此它不會忠實於您的原始數據,但如果我們假設您的 plot 是這樣的:
p <- plot_model(model, type = "pred", terms = c("predictor [all]", "conditions")) +
xlab("Xlab") +
ylab("Ylab") +
theme_minimal() +
ggtitle("Title")
p
然后我們可以像這樣添加預測變量的直方圖:
p + geom_histogram(data = d, inherit.aes = FALSE,
aes(x = predictor, y = ..count../1000),
fill = "gray85", colour = "gray50", alpha = 0.3)
如果你想在 ggplot 中做所有事情,你需要記住告訴geom_smooth
你的 glm 是一個概率 model,否則它只會適合正常的線性回歸。 對於這個示例,我也復制了調色板,但請注意組的平滑線從它們的最低 x 值開始,而不是外推回 0。
ggplot(d, aes(x = predictor, y = DV, color = conditions))+
geom_smooth(method = "glm", aes(fill = conditions),
method.args = list(family = binomial(link = "probit")),
alpha = 0.15, size = 0.5) +
xlab("Xlab") +
scale_fill_manual(values = c("#e41a1c", "#377eb8")) +
scale_colour_manual(values = c("#e41a1c", "#377eb8")) +
ylab("Ylab") +
theme_minimal() +
ggtitle("Title") +
geom_histogram(aes(y = ..count../1000),
fill = "gray85", colour = "gray50", alpha = 0.3)
數據
set.seed(69)
n_each <- 500
predictor <- rgamma(2 * n_each, 2.5, 3)
predictor <- 1 - predictor/max(predictor)
log_odds <- c((1 - predictor[1:n_each]) * 5 - 3.605,
predictor[n_each + 1:n_each] * 0 + 0.57)
DV <- rbinom(2 * n_each, 1, exp(log_odds)/(1 + exp(log_odds)))
conditions <- factor(rep(c(" ", " "), each = n_each))
d <- data.frame(DV, predictor, conditions)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.