Ggplot2 - change color of `geom_rect` on stack

I'm trying to plot a complex barplot using ggplot2::geom_bar

back row shading (using ggplot2::geom_rect()

) according to a categorical variable like this:

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 do I change the shading colors? I've tried it scale_fill_manual(values = c("white", "gray53"))

, but it seems like ggplot2

there is no multi-element aesthetic ( https://github.com/hadley/ggplot2/issues/578 ). Is there any other way to get the desired result?

+3


source to share


1 answer


Yes, instead of putting your colors in aes()

, put them outside (that's why they are used as-is). Since it is outside of the call, aes()

you will have to use an explicit one fill=shading$col

, not fill=col

, and shading$col

should have the color name that you are after (instead of a variable being 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)

      

+5


source







All Articles