Search code examples
rggplot2geom-point

Changing specific value color with ggplot


I am using geom_point() with ggplot to essentially create the equivalent of a -coefplot- with coefficients of 5 different models on one plot.

Is it possible for me to change the color of just one point (and corresponding CI bars)? What about the color/font/etc. of an individual axis tick label? For example, if I only want to make the font bold for the label for Model 3 and make Model 3's coefficient point (+ CI bars) red (or any other color to distinguish it). I've tried scale_fill_manual but that didn't seem to do the trick.

My current code (with scale_x_discrete, the names of the models are just Model 1, 2, 3, etc. and I'm putting them in order there):

ggplot(d, aes(x = var, y = coef)) + 
  geom_point() + 
  geom_pointrange(aes(ymin = cilow, ymax = ciupper)) + 
  scale_x_discrete(limits = model_order, labels = model_label) + 
  theme_minimal()

Solution

  • You can use a condition to color only the point and CI that you want. ifelse(test to select your group, color name if yes, color name if not).

    library(tidyverse)
    
    df=iris %>% 
      group_by(Species) %>% 
        summarise(min=min(Petal.Length),
                  max=max(Sepal.Length),
                  mean=(min+max)/2)  
    ggplot(df,aes(Species, mean,color=Species)) +
      geom_point() +
      geom_pointrange(aes(ymin = min, ymax = max))+
      scale_color_manual(values = ifelse(df$Species=="setosa","red","black"))
    

    To change your axis labels, you can use ggtext as indicated in this post

    library(ggtext)
    library(glue)
    
    highlight = function(x, pat, color="black", family="") {
      ifelse(grepl(pat, x), glue("<b style='font-family:{family}; color:{color}'>{x}</b>"), x)
    }
    ggplot(df,aes(Species, mean,color=Species)) +
      geom_point() +
      geom_pointrange(aes(ymin = min, ymax = max))+
      scale_x_discrete(labels=function(x) highlight(x, "setosa", "purple")) +
      scale_color_manual(values = ifelse(df$Species=="setosa","red","black"))
      theme_bw()+
      theme(axis.text.x=element_markdown(size=15))
    

    It didn't work with theme_minimal, so I used a different one.

    Plot