'Is it somehow possible to create a bar chart in ggplot2 using a multi grouping system as shown in this graph?
[graph][1]
I want to create a bar chart grouping the variables as shown at the bottom of the graph (environmental surfaces and processing steps), is there any geom that allows to create this in ggplot2? [1]: https://i.stack.imgur.com/2rQd9.png
Solution 1:[1]
You can get the basics with geom_tile(), but you'll manually have to specify where on the y-axis the tiles need to be placed.
library(ggplot2)
df <- expand.grid(first_level = LETTERS[1:4], second_level = LETTERS[5:7],
third_level = LETTERS[8:9])
df$value <- rpois(nrow(df), lambda = 2)
ggplot(df, aes(interaction(second_level, first_level), value)) +
geom_col(aes(fill = third_level), position = position_dodge()) +
geom_tile(
aes(y = -0.1, height = 0.2, fill = second_level),
colour = "white"
) +
geom_tile(
aes(y = -0.3, height = 0.2, fill = first_level),
colour = "white"
)

To get more control over how every level is displayed, you can use the {ggnewscale} package.
ggplot(df, aes(interaction(second_level, first_level), value)) +
geom_col(aes(fill = third_level), position = position_dodge()) +
scale_fill_manual(values = c("blue", "yellow")) +
ggnewscale::new_scale_fill() +
geom_tile(
aes(y = -0.1, height = 0.2, fill = second_level),
colour = "white"
) +
scale_fill_manual(values = c("red", "blue", "grey")) +
ggnewscale::new_scale_fill() +
geom_tile(
aes(y = -0.3, height = 0.2, fill = first_level),
colour = "white"
) +
scale_fill_manual(values = c("purple", "cyan", "yellow", "green")) +
scale_y_continuous(expand = c(0, 0, 0.05, 0))

Created on 2022-05-17 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | teunbrand |
