Home > Software engineering >  Change plot colour by positive / negative value for modelplot()
Change plot colour by positive / negative value for modelplot()

Time:12-18

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,

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related