简体   繁体   中英

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

I want to graph an interaction effect between two variables with one outcome in R. While I can successfully produce a graph using sjPlot:plot_model(), the interaction plot does not resize when I adjust the x-axis values. Instead, the graph that's plotted is always that of the original-size while the x- and y-axis will adjust. Below is an example using the mtcars data in R.

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 的成功交互图的图片

I can get a graph like this in my own code. However, when I attempt to alter the x- and y-axes as seen below, the grid expands, but the graph itself does not.

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

Picture of successfully graphed interaction with wildly exaggerated adjustments to the axes. The graph does not extend but the grid does.

What code can I use to adjust both the lines of my interaction effect AND those of the grid? Adjusting post-hoc with

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

creates the same issue.

Post-hoc extending the graph creates the same issue.

plot_model will only plot interactions over the range of your original data. It's really not difficult to do it directly in ggplot though by feeding whatever x values you want into 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")

Created on 2022-05-21 by the reprex package (v2.0.1)

plot_model allow you to choose the range of the plot just adding the range in square braquets next to the selected variable <<[min,max]>>.

I think the easiest way would be the following:

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

You can find more details here: https://strengejacke.github.io/sjPlot/articles/plot_marginal_effects.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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