简体   繁体   中英

ggplot2 Use text colour as a legend for fill

I am using ggplot with a geom_bar layer.

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)

I would like to reproduce factor annotations I have seen that is different to ggplot default guides. Instead of the fill aesthetic being in a legend to the right of the panel with text alongside each fill colour, I would like the text to be coloured and present in the panel.

This is the default option:

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

在此处输入图片说明

This is what I have done to mimic the style I am after:

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)

在此处输入图片说明

Some problems:

  • The legend position is hardcoded. (Here the max of the stacks, which is fine if the bars are of a similar height). Can the text be in the top right of the chart background?
  • The text is centre-aligned. Using hjust=0 makes it left-aligned, but with the left margin of the text to the middle of the category. (This might be solved by solving the first point.)
  • Bonus: if the category text labels are long, can the line breaks be "nicely" programmed?

I ended up choosing annotate() to achieve your goal. You can specify the colours for texts in this way.

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")

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM