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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With