Search code examples
rplotlogistic-regressionsjplot

Combine 2 Predicted Probabilities graphs in R with SjPlot Package


Lets say I have this code:

dt <- data.frame(x = (1:9), z = c(6,5,3,7,8,3,1,6,7), y = c(1,0,1,1,0,0,0,1,0))
model1 <- glm(y ~ x + z, family = binomial(link = "logit"),
              data = dt)
model2 <- glm(y ~ x + z, family = binomial(link = "logit"),
              data = dt)
summary(model1)
summary(model2)
library(sjPlot)
m <- plot_model(model1, title = "Predicted probabilities", type = "pred", terms = "x")
n <- plot_model(model2, title = "Predicted probabilities", type = "pred", terms = "x")

I want to combine both graphs so I can just save them in one file. In both graphs you can find predicted probabilities from the sjPlot Package.

How can I achieve that?

I tried par(mfrow=c(2,2)) already but it does not work at all.

Any help appreciated!


Solution

  • Since you tried the par() function i assume you want to create the two graphs side by side. You can achieve this with the grid.arrange() function of the library gridExtra which looks as follows: gridExtra

    Used code:

    library(sjPlot)
    library(gridExtra)
    
    dt <- data.frame(x = (1:9), z = c(6,5,3,7,8,3,1,6,7), y = c(1,0,1,1,0,0,0,1,0))
    
    model1 <- 0
    model2 <- 0
    
    model1 <- glm(y ~ x + z, family = binomial(link = "logit"),
                  data = dt)
    model2 <- glm(y ~ x^4 + z, family = binomial(link = "logit"),
                  data = dt)
    summary(model1)
    summary(model2)
    
    m <- plot_model(model1, title = "Predicted probabilities", type = "pred", terms = "x")
    n <- plot_model(model2, title = "Predicted probabilities", type = "pred", terms = "x")
    
    grid.arrange(m, n, ncol = 1, heights = c(1, 1))
    

    If you want them side by side and not one above the other, just change the ncol value to 2