Hugh
Hugh

Reputation: 16089

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

enter image description here

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)

enter image description here

Some problems:

Upvotes: 0

Views: 1040

Answers (1)

jazzurro
jazzurro

Reputation: 23574

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

enter image description here

Upvotes: 1

Related Questions