繁体   English   中英

右|| 在 sjPlot::plot_model() 中调整 x 轴

[英]R || Adjusting x-axis in sjPlot::plot_model()

我想在 R 中用一个结果绘制两个变量之间的交互效应。虽然我可以使用 sjPlot:plot_model() 成功生成图形,但当我调整 x 轴值时交互图不会调整大小。 相反,绘制的图形始终是原始大小的图形,而 x 轴和 y 轴将调整。 下面是在 R 中使用 mtcars 数据的示例。

library(sjPlot)
library(sjmisc)
library(ggplot2)
mtcars.df <- mtcars
fit <- lm(mpg ~ hp * disp, data = mtcars.df)
plot_model(fit, type = "pred", terms = c("hp", "disp"))

来自 mtcars 的成功交互图的图片

我可以在自己的代码中得到这样的图表。 但是,当我尝试如下所示更改 x 轴和 y 轴时,网格会扩展,但图形本身不会。

plot_model(fit, type = "pred", terms = c("hp", "disp"), axis.lim = list(c(0,150),c(0,200)))

成功绘制交互图,并对轴进行了夸张的调整。 图形不会延伸,但网格会延伸。

我可以使用什么代码来调整交互效果的线条和网格的线条? 调整事后

plot_model(fit, type = "pred", terms = c("hp", "disp"))+xlim(0,150)

产生同样的问题。

事后扩展图会产生同样的问题。

plot_model只会在原始数据范围内绘制交互。 通过将您想要的任何 x 值输入predict ,直接在 ggplot 中执行它真的不难:

library(ggplot2)

mtcars.df <- mtcars
fit <- lm(mpg ~ hp * disp, data = mtcars.df)

new_df       <- expand.grid(hp = 0:300, disp = c(106.78, 230.72, 354.66))
predictions  <- predict(fit, new_df, se = TRUE)
new_df$mpg   <- predictions$fit
new_df$upper <- new_df$mpg + 1.96 * predictions$se.fit
new_df$lower <- new_df$mpg - 1.96 * predictions$se.fit
new_df$disp  <- factor(new_df$disp)

ggplot(new_df, aes(hp, mpg)) +
  geom_ribbon(aes(ymax = upper, ymin = lower, fill = disp), alpha = 0.3) +
  geom_line(aes(color = disp)) +
  scale_fill_brewer(palette = "Set1") +
  scale_color_brewer(palette = "Set1")

reprex 包于 2022-05-21 创建 (v2.0.1)

plot_model允许您选择绘图的范围,只需在所选变量 <<[min,max]>> 旁边添加方括号中的范围。

我认为最简单的方法如下:

plot_model(fit, type = "pred", terms = c("hp [0,300]", "disp"))

您可以在此处找到更多详细信息: https ://strengejacke.github.io/sjPlot/articles/plot_marginal_effects.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM