r - ggplot2 - Change `geom_rect` colour in a stacked barplot -


i trying plot stacked barplot using ggplot2::geom_bar backgroud shading (using ggplot2::geom_rect()) according categorical variable follows:

shading <- data.frame(min = seq(from = 0.5, = max(as.numeric(as.factor(diamonds$clarity))), = 1),                       max = seq(from = 1.5, = max(as.numeric(as.factor(diamonds$clarity))) + 0.5, = 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 change colours of shading? have tried scale_fill_manual(values = c("white", "gray53")), seems multiple scale aesthetics not possible in ggplot2 (https://github.com/hadley/ggplot2/issues/578). there way desired result ?

yes, instead of putting colours in aes(), put them outside (so used as-is). since it's outside aes() call have use explicit fill=shading$col rather fill=col, , shading$col should have colour name after (rather variable interpreted 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) 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -