在标签中使用多种颜色

时间:2016-12-02 21:52:17

标签: r ggplot2

在下面的图表中,我希望子组A的标签中的每个三角形与他们所指的子组的颜色相匹配(绿色,蓝色,紫色)。这有可能吗?

library(tibble)
library(dplyr)
library(ggplot2)
library(scales)

example_tibble <- tibble(Subgroup = c("A", "B", "C", "D"),
                         Result = c(0.288, 0.204, 0.206, 0.182),
                         A_vs_B = rep(1, 4),
                         A_vs_C = rep(1, 4),
                         A_vs_D = rep(1, 4))

ggplot(example_tibble, aes(x = Subgroup, y = Result, fill = Subgroup)) + 
  geom_bar(stat = "identity") + geom_text(aes(label = 
      paste0(percent(Result), 
             if_else(A_vs_B == 1 & Subgroup == "A", sprintf("\u25b2"), ""),
             if_else(A_vs_C == 1 & Subgroup == "A", sprintf("\u25b2"), ""),
             if_else(A_vs_D == 1 & Subgroup == "A", sprintf("\u25b2"), "")),
             colour = Subgroup), hjust = -.25) + 
  coord_flip() + scale_y_continuous(limits = c(0,.5), labels = percent)

enter image description here

0 个答案:

没有答案