首页 文章

ggplot2使用文本颜色作为填充图例

提问于
浏览
0

我正在使用带有 geom_bar 图层的ggplot .

library(ggplot2)
library(dplyr)
library(reshape2)

dat <- data.frame(
  A = c(1, 1, 0.5),
  B = c(1.2, 1, 0.6),
  FF = c("F1", "F2", "F3")
  ) %>%
  mutate(Other = max(A,B))
dat.m <- melt(dat)

我想重现我看到的与 ggplot 默认指南不同的因子注释 . 我希望文本在面板中显示颜色并显示在面板右侧的图例中,而不是 fill 美审在面板右侧的图例中 .

这是默认选项:

ggplot(filter(dat.m, variable != "Other")) + 
  geom_bar(aes(x = variable, y = value, fill=FF),
           stat="identity")

enter image description here

这就是我模仿我追求的风格所做的:

ggplot() + 
  geom_bar(filter(dat.m, variable != "Other"), 
           mapping = aes(x = variable, y = value, fill = FF), 
           stat="identity") + 
  geom_text(filter(dat.m, variable == "Other"), 
            mapping = aes(x = variable, y = value, col = FF, label=FF),
            position="stack", fontface="bold") +
  guides(fill = FALSE, colour=FALSE, text=FALSE)

enter image description here

一些问题:

  • 图例位置是硬编码的 . (这里是堆栈的 max ,如果条形高度相似则没问题) . 文本可以位于图表背景的右上角吗?

  • 文本居中对齐 . 使用 hjust=0 使其左对齐,但文本的左边距位于类别的中间 . (这可以通过解决第一点来解决 . )

  • 额外奖励:如果类别文本标签很长,可以将换行符编程为"nicely"吗?

1 回答

  • 1

    我最终选择 annotate() 来实现你的目标 . 您可以通过这种方式指定文本的颜色 .

    ggplot(data = filter(dat.m, variable != "Other"), 
           aes(x = variable, y = value, fill = FF)) + 
           geom_bar(stat="identity") + 
           annotate("text", x = 2.55, y = 2.6, label = "F1", color = "#F8766D") +
           annotate("text", x = 2.55, y = 2.7, label = "F2", color = "#00BA38") +
           annotate("text", x = 2.55, y = 2.8, label = "F3", color = "#619CFF") +
           theme(legend.position="none")
    

    enter image description here

相关问题