我想有条件地为 ggplot 中的注释栏着色以标记字符。我在这里发布以下示例
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)
但不幸的是它似乎不起作用。你能建议一些替代方案吗?谢谢
看起来
ggpubr::stat_pvalue_manual
在幕后与 geom_text
一起工作,因此您需要添加一种 scale_color_manual
图层来部署正确的颜色;因为您没有将组写为因子,所以我将使用 scale_color_identity
来保留正确的颜色顺序:
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")
如果您想用相应的颜色填充条形,只需将
geom_col() +
更改为 geom_col(aes(fill = my_data$colors)) +
并添加 scale_fill_identity(palette = my_data$color) +
。最后注意,stat_pvalue_manual
填写的正确参数是color
而不是colour
。