Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - Change `geom_rect` colour in a stacked barplot

Tags:

plot

r

ggplot2

I am trying to plot a stacked barplot using ggplot2::geom_bar with backgroud shading (using ggplot2::geom_rect()) according to a categorical variable as follows:

shading <- data.frame(min = seq(from = 0.5, to = max(as.numeric(as.factor(diamonds$clarity))), by = 1),
                      max = seq(from = 1.5, to = max(as.numeric(as.factor(diamonds$clarity))) + 0.5, by = 1),
                      col = c(0,1))

ggplot() + 
  theme(panel.background = element_rect(fill = "transparent")) +
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  geom_rect(data = shading,
            aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf,
                fill = factor(col), alpha = 0.1)) +
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  guides(alpha = FALSE)

enter image description here

How to change the colours of the shading? I have tried scale_fill_manual(values = c("white", "gray53")), but it seems that multiple scale aesthetics are not possible in ggplot2 (https://github.com/hadley/ggplot2/issues/578). Is there another way to get the desired result ?

like image 617
Crops Avatar asked Jul 23 '15 22:07

Crops


1 Answers

Yes, instead of putting your colours in the aes(), put them outside (so they are used as-is). Since it's outside the aes() call you will have to use an explicit fill=shading$col rather than fill=col, and shading$col should have the colour name you are after (rather than a variable interpreted as a factor).

shading$col <- ifelse(shading$col, 'white', 'gray53')
ggplot() + 
  theme(panel.background = element_rect(fill = "transparent")) +
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  geom_rect(data = shading,
            aes(xmin = min, xmax = max, ymin = -Inf, ymax = Inf, alpha = 0.1),
                fill=shading$col) + # <-- here
  geom_bar(data = diamonds, mapping = aes(clarity, fill=cut)) +
  guides(alpha = FALSE)
like image 106
mathematical.coffee Avatar answered Nov 08 '22 02:11

mathematical.coffee