如何在同一个图上绘制标准差增加和标准差减少的边际效应?

问题描述 投票:0回答:1

我想在同一个图上绘制模型标准差增加和标准差减少的边际效应。我正在使用

marginaleffects
包,但我愿意接受其他解决方案。

这是一个例子,假设我有以下模型:

library(marginaleffects)
library(ggplot2)

mtcars2 <- within(mtcars, hp <- scale(hp)[,1])
mod <- lm(mpg ~ hp * disp + factor(am), data = mtcars2)

我想获得

hp
的标准差增加和标准差减少。标准差为:

sd(mtcars$hp)
> sd(mtcars$hp)
[1] 68.56287

然后,我可以使用代码单独绘制每个标准差:

plot1 <- plot_comparisons(mod, variables = list(hp = 68.56287), condition = "disp")
plot1

plot2 <- plot_comparisons(mod, variables = list(hp = -68.56287), condition = "disp")
plot2

我不想将这些值放在两个图中,而是希望将它们放在一个图中。我怎样才能做到这一点?

编辑:按照文森特的建议,我想我做到了:

plot1 <- plot_comparisons(mod, variables = list(hp = 68.56287), condition = "disp", draw = F)
plot1
plot2 <- plot_comparisons(mod, variables = list(hp = -68.56287), condition = "disp", draw = F)
plot2

plot1$example <- 1
plot2$example <- 2

plots <- rbind(plot1, plot2)

ggplot(plots, aes(disp, estimate, fill=factor(example), color = example))+
  geom_line()+
  geom_ribbon(aes(ymin=conf.low, ymax=conf.high, color=NULL), alpha=0.2)

现在我必须弄清楚如何修复标签,然后我就很好了。

r ggplot2 plot marginal-effects r-marginaleffects
1个回答
0
投票

您可以使用 ggeffects-package,它可以让您轻松创建特定值的预测或边际效应图:

library(ggeffects)

mtcars2 <- within(mtcars, hp <- scale(hp)[,1])
mod <- lm(mpg ~ hp * disp + factor(am), data = mtcars2)

# focal terms specified as strings
ggpredict(mod, c("disp", "hp[-68.5, 68.5]")) |> plot()


# or as list
ggpredict(mod, list(disp = seq(100, 500, 10), hp = c(-68.5, 68.5))) |> plot()

© www.soinside.com 2019 - 2024. All rights reserved.