how to order variables in plot_coeffs forestplot in R

215 Views Asked by At

I have several models I am visualizing using plot_summs in R, and I want to specify the order that the covariates are displayed. Here is an example of what my data looks like (numbers are made up, but the format is the same as my actual dataset):

Mongoose Viverrid LgDkr Por AllSqr DT_River cbFI sqRc DT_CM sqVl lnMB DT_Human lnRd lnPv
1 0 1 0 0 0.88 0.02 0.76 -0.34 0.45 -0.21 0.33 0.89 -0.01
0 0 1 1 0 0.56 0.22 -0.03 0.41 -0.82 0.09 0.12 0.07 0.55
1 1 0 0 1 0.22 0.98 -0.16 0.09 0.15 -0.91 0.22 0.79 0.11

I've used the following code:

fit1 <- glm(Mongooses ~ DT_River + DT_Human, data = df, family = binomial)
fit2 <- glm(Viverrids ~ cbFI, data = df, family = binomial)
fit3 <- glm(LgDkr ~ DT_River + lnRd + lnMB + DT_Human, data = df, family = binomial)
fit4 <- glm(Por ~ cbFI + sqVl, data = df, family = binomial)
fit5 <- glm(AllSqr ~ sqVl + DT_River + lnMB, data = df, family = binomial)

plot_coefs(fit1,fit2,fit3,fit4,fit5, ci_level = 0.95, colors = "Rainbow",
           model.names = c("Mongooses", "Viverrids", "Large Duikers", "Porcupines", "Squirrels")) 
           + coord_cartesian(xlim = c(-2.5, 2.5))

But my plot is coming out with the coefficients in a different order than my dataframe! enter image description here (ex. DT_Human is showing up after DT_River, when I'd like it to show up in the same order as my dataframe, so it should be at the bottom...)

It seems like plot_coeffs is showing the variables in the order they show up in the models, but how do I override this?

1

There are 1 best solutions below

0
On

You can add a scale_y_discrete with the correct orderings passed to the limits argument:

jtools::plot_coefs(fit1,fit2,fit3,fit4,fit5, ci_level = 0.95, colors = "Rainbow",
           model.names = c("Mongooses", "Viverrids", "Large Duikers", 
                           "Porcupines", "Squirrels")) + 
           coord_cartesian(xlim = c(-2.5, 2.5)) +
           scale_y_discrete(limits = rev(names(df)[c(6, 7, 10:13)]))

enter image description here