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
It seems that
ggpubr::stat_pvalue_manual
works withgeom_text
behind the scenes so you need to add a kind ofscale_color_manual
layer to deploy the correct colors; since you didn't write your groups as factors then I'll usescale_color_identity
to preserve the correct order of colors:If you want to fill the bars with the respective colors, just change
geom_col() +
togeom_col(aes(fill = my_data$colors)) +
and addscale_fill_identity(palette = my_data$color) +
. Last but not least note that the correct parameter to be filled instat_pvalue_manual
iscolor
instead ofcolour
.