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

How to get overlapped rectangular bars in ggplot?

I am trying to create 3 layers of rectangles each with different color on top of each other to get something like below image:

enter image description here

Data:

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

library(tidyverse)

df_vaccination <- data.frame(type = c('Population', 'First.Dose.Administered', 'Second.Dose.Administered'),
           count = c(1366400000, 952457943, 734608556))

Code tried:

df_vaccination %>% 
  
  ggplot()+
  geom_rect(aes(xmin = 0, ymin = 0, xmax = count, ymax = 0,
                   size = 10, lineend = 'round',
                   alpha = 0.5, fill = type)) +
  scale_fill_manual(values = c("#d8b365", "orange", "#5ab4ac")) +
  
  theme_clean() +
  scale_x_continuous(labels = unit_format(scale = 1e-7, unit = "Cr")) +
  guides(color = guide_legend(order = 1),
         size = FALSE,
         alpha = FALSE)

Result I am getting is blank plot when I am using geom_rect() & scale_fill_manual(). I am not sure why am I getting blank rectangle:
enter image description here

>Solution :

Convert type column to ordered factor so that largest number plots first, then use geom_col with x = 1. This will make the bars to plot on top of each other, lastly flip the coordinates:

df_vaccination$type <- factor(df_vaccination$type, levels = df_vaccination$type)

ggplot(df_vaccination, aes(x = 1, y = count, fill = type))+
  geom_col() +
  scale_fill_manual(values = c("#d8b365", "orange", "#5ab4ac")) +
  coord_flip() +
  theme_void()

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