I’m trying to create a stacked bar chart using ggplot but unable to add multiple stacks to my bar. Im trying to get each stack to show the breakdown of primary, secondary and post16 (represented by different colours), whilst the overall hight represents the total. As you can see below the bars aren’t quite correct as i am missing the coours to represent the breakdown, I’m pretty sure this will comes from the geom_col() argument but unsure of the fix.
data:
df <- read_table("region total primary secondary post16
East 21 4 8 9
Mid 28 3 15 10
North 7 2 4 1
South 13 3 5 5")
code:
ggplot(df, aes(x = as.factor(region), y = total, fill = "total")) +
geom_col() +
geom_col(aes(y = primary, fill = "prim")) +
geom_col(aes(y = secondary, fill = "seco")) +
geom_col(aes(y = post16, fill = "p16")) +
coord_flip()
Current plot
>Solution :
A bit of a re-write here. The key is transforming the data into long form:
library(tidyverse)
df <- read_table("region total primary secondary post16
East 21 4 8 9
Mid 28 3 15 10
North 7 2 4 1
South 13 3 5 5")
df %>%
dplyr::select(-total) %>%
pivot_longer(-region) %>%
mutate(name = fct_relevel(name, "primary", "secondary", "post16")) %>%
ggplot(aes(x = region, y = value, fill = name)) +
geom_col() +
coord_flip()

