How to color conditionally to character in label the annotations bars

60 views Asked by At

I would like to concitionally color annotations bars in ggplot to label character. I am posting the following example here

library(ggplot2)
library(rstatix)

color_mapping <- function(label) {
  if (grepl("A", label)) {
    return("orange")  
  } else if (grepl("B", label)) {
    return("purple") 
  } else {
    return("aquamarine") 
  }

}

my_data <- data.frame(
  group1 = c("A", "B", "C"),
  group2 = c("D", "E", "G"),
  p = c(0.01, 0.05, 0.001),
  y.position = c(0.8, 0.7, 0.9),
  label = c(
    "A vs D: p=0.037  -  ns",
    "B vs E: p=5.78e-06  -  ****",
    "C vs D: p=0.005  -  *"
  )
)

my_data$color <- sapply(my_data$label, color_mapping)

my_plot <- ggplot(my_data, aes(x = group1, y = y.position)) +
  geom_bar(stat = "identity") +
  stat_pvalue_manual(data = my_data, label = "label", colour = my_data$color)

But unfortunately it does not seem to work. Could you suggest some alternatives? Thanks

1

There are 1 answers

0
user123456 On

It seems that ggpubr::stat_pvalue_manual works with geom_text behind the scenes so you need to add a kind of scale_color_manual layer to deploy the correct colors; since you didn't write your groups as factors then I'll use scale_color_identity to preserve the correct order of colors:

  ggplot(my_data, aes(x = group1, y = y.position)) +
    geom_col() +
    stat_pvalue_manual(data = my_data, label = "label", color = "color") +
    scale_color_identity(palette = my_data$color) +
    theme(legend.position = "none")

enter image description here

If you want to fill the bars with the respective colors, just change geom_col() + to geom_col(aes(fill = my_data$colors)) + and add scale_fill_identity(palette = my_data$color) +. Last but not least note that the correct parameter to be filled in stat_pvalue_manual is color instead of colour.