【问题标题】:R || Adjusting x-axis in sjPlot::plot_model()右 ||在 sjPlot::plot_model() 中调整 x 轴
【发布时间】:2022-07-22 01:20:39
【问题描述】:

我想用 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"))

我可以在自己的代码中得到这样的图表。但是,当我尝试如下所示更改 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)

产生同样的问题。

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

【问题讨论】:

    标签: r plot graph sjplot


    【解决方案1】:

    plot_model 只会绘制原始数据范围内的交互。直接在 ggplot 中执行此操作实际上并不难,尽管通过将您想要的任何 x 值输入predict:

    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 package (v2.0.1) 于 2022-05-21 创建

    【讨论】:

    • 嗨。我看到你解决了一个与在 gg​​plot2 上添加饼图到地图相关的问题,也许你能分享这个答案吗?谢谢!
    • @user007 我不知道你指的是哪个问题。你能分享一个链接吗?如果我已经回答过了,分享是什么意思?
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多