Search code examples
rggplot2aesr-forestplot

Change colour of a specific diamond on a forest plot using ggplot2


I am trying to highlight one specific diamond of a variable on my forest plot using ggplot but I cannot find how to include this. I am trying to change the colour of "Periodontitis (Yes)".

dataset_unstratified$variables <- factor(dataset_unstratified$variables
                                         , levels = c("Intercept (Skeletal Muscle Mass Index)","Periodontitis (Yes)", "Sex(Men)", "Age", "Body-Mass Index", "Smoker", "Former Smoker",
                                                      "Diabetes","Prediabetes","Education (Low)","Education (Medium)","Daily energy intake",
                                                      "Daily protein intake", "Vitamin D2 and D3", "Bone Mineral Density"))
dataset_unstratified <- dataset_unstratified[order(dataset_unstratified$variables), ]

plot_width <- 100
wrapper <- function(x)  {   
  paste(strwrap(x, width = plot_width), collapse = "\n") 
}

plot1 <- ggplot(dataset_unstratified, aes(y=variables, x=coefficients)) +
  geom_point(shape = 18, size = 5) +  
  theme(axis.title.y = element_blank()) +
  xlab("Beta-coefficients with 95% Confidence Intervals") +  
  ylab("Model variables") + theme(axis.title.y = element_blank()) +
  labs(title = wrapper("a) SMMI and periodontitis"))+ 
  geom_errorbarh(aes(xmin = `2.5 %`, xmax = `97.5 %`), height = 0.25) +
  geom_vline(xintercept = 0, color = "blue", linetype = "dashed", cex = 1, alpha = 0.5)

Solution

  • Your code is currently not reproducible, but you should be able to achieve your desired output by creating a color palette of boring gray colors and then injecting a "highlight" color (e.g., red) into that color palette based on a specific level of a factor (e.g., hp). Based on this post.

    library(tidyverse)
    library(RColorBrewer)
    data(mtcars)
    
    # make a long dataframe
    df <- mtcars %>% 
      rownames_to_column(var = "rowname") %>%
      pivot_longer(cols = -rowname) %>%
      mutate(name = as.factor(name)) 
    
    ref <- "hp" # specify the name of the level you want to
    varlength <- length(levels(df$name)) # specify the variable that goes on the final y-axis
    myColors <- colorRampPalette(brewer.pal(8, "Greys"))(varlength) # get a bunch of gray colors
    names(myColors) <- levels(df$name)
    myColors[names(myColors)==ref] <- "red" # specify your "highlight" color
    colScale <- scale_color_manual(name = "grp", values = myColors) # turn into a ggplot object
    
    ggplot(df, aes(y = name, x = value, color = name)) +
      geom_point(shape = 18, size = 5) + colScale
    

    enter image description here