1

I am preparing forest plots with regression coefficients using sjPlot package. How can I customize the line color of regression coefficients to have one color for each coefficient?

I have tried to use the argument colors = c("blue", "red", "black") within the plot_model function, but it did not work. I have also tried to use different palettes combined with scale_color_manual, but it did not work either.

Here is an example from sjPlot package:

library(sjPlot)
library(sjmisc)
data(efc)

#I used log before each predictor to have an example of confidence interval
fit <- lm(tot_sc_e ~ log(c161sex) + log(e17age) + log(c160age), data = efc)

plot_model(fit, colors = c("blue", "red", "black"))

It gives me a plot with two blue lines and one red line. No black line in the plot!

enter image description here

Trying to use other ways did not help:

plot_model(fit, colors = NULL)+
  scale_fill_sjplot(palette = "viridis", discrete = TRUE)+
  scale_color_viridis(discrete = TRUE)

It actually uses the viridis palette, but again, two purple lines and one yellow line. And it returns the following messages:

"Scale for 'fill' is already present. Adding another scale for 'fill', which will replace the existing scale." "Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale."

enter image description here

If I set colors = NULL in the code, it should not return these messages, should it?

I would appreciate any help to get one different color for each predictor. Note: this plot will be combined with other plots with the same predictors. Therefore, I want to have them with the same color in both plots to improve the readability.

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
Jhonny
  • 15
  • 6

1 Answers1

1

By default, the colour / fill aesthetics are mapped to whether each coefficient is positive or negative. To override this & tell sjPlot to treat each of the 3 coefficients as its own group, you can specify group.terms = c(1, 2, 3) as a parameter in plot_model:

plot_model(fit, 
           group.terms = c(1, 2, 3), 
           colors = c("blue", "red", "black"))

with group terms set

The function's default behaviour also sorts the coefficients alphabetically, which messes up the blue-red-black sequence. To keep the original order of coefficients (i.e. the order in fit), we can additionally specify order.terms in plot_model:

plot_model(fit, 
           group.terms = c(1, 2, 3), 
           order.terms = c(1, 2, 3),
           colors = c("blue", "red", "black"))

plot

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
  • Thank you very much for your answer @Z.Lin. It was nice that you showed the `order.terms` argument because I tried to use `group.terms` coupled with `sort.est = TRUE` and I got an error: `Error: fun must return a single number per group`. When I replaced `sort.est = TRUE` by `order.terms`, it worked fine. – Jhonny Apr 10 '19 at 10:19