Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a stacked bar chart

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

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading