2

I'm trying to change the color of coefficients in a forest plot using modelplot(), so the that positive values are one color, and negative values another, as with the separate plotmodel() function,

library(modelsummary)
modelplot(
    model1,
    coef_omit = 'Interc'
    ) + 
      xlim(-0.75, 0.75) +
      theme_gray() +
     labs(
    x = "Coefficient estimates and \n 95 pc confidence intervals"
  )

but I can't figure out how to do it. I've experimented using scale_colour_gradientn() and similar but they don't work.

Does anyone have any suggestions for this?

thanks

Vincent
  • 15,809
  • 7
  • 37
  • 39

2 Answers2

5

You can do this by mapping the value estimate > 0 to the color aesthetic:

library(modelsummary)
library(ggplot2)

model1 <- lm(hp ~ vs + drat, mtcars)

modelplot(model1) + 
  aes(color = estimate > 0) +
  scale_color_manual(values = c("red3", "green4"), guide = "none")

Created on 2022-12-17 with reprex v2.0.2

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • This is very cool, thanks. I took the liberty to add a similar example to the `modelplot` vignette: https://vincentarelbundock.github.io/modelsummary/articles/modelplot.html#conditional-colors-and-shape – Vincent Dec 17 '22 at 17:55
  • @vincent wow! Great work! – Allan Cameron Dec 17 '22 at 22:55
3

You could use ggplot_build to convert the color layer if the x-coordinate of your coefficient is lower or higher than 0. Here is a reproducible example with mtcars dataset:

# Example model using mtcars data
model1 <-  lm(vs ~ carb + mpg + cyl, data = mtcars)

library(ggplot2)
library(modelsummary)
p<-modelplot(
  model1,
  coef_omit = 'Interc'
) + 
  xlim(-0.75, 0.75) +
  theme_gray() +
  labs(
    x = "Coefficient estimates and \n 95 pc confidence intervals"
  )

# ggplot_build
q <- ggplot_build(p)

# change color conditionally
q$data[[1]]$colour <- with(q, ifelse(data[[1]]$x < 0, 'red', 'green'))
# turn back
q <- ggplot_gtable(q)

# Visualize
plot(q)

Created on 2022-12-17 with reprex v2.0.2

And if your coefficient is positive:

# Example model using mtcars data
model1 <-  lm(-vs ~ carb + mpg + cyl, data = mtcars)

# Visualize
plot(q)

Created on 2022-12-17 with reprex v2.0.2

You can change the color to whatever you want.

Quinten
  • 35,235
  • 5
  • 20
  • 53