简体   繁体   中英

ggplot2 - Change `geom_rect` colour in a stacked barplot

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)

在此输入图像描述

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 ?

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)

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