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

Order the stacked barplot by proportion or percent in R

I can order my plot based on count but not by proportion. I want to bars on x-axis to be arranged by proportion of "c". Here is my code

long<- data.frame(
      Name = c("abc","abc","abc","gif","gif","gif","xyz","xyz","xyz"),
      variable = c("a","b","c","a","b","c","c","b","a"),
      value = c(4,6,NA,2,8,1,6,NA,NA))
    
    
long_totals <- long %>%
      group_by(Name) %>%
      summarise(Total = sum(value, na.rm = T))
    
        p<-long %>%
    mutate(variable = fct_relevel(variable, c("c", "b", "a"))) %>%
                  arrange(variable) %>%        
                  mutate(Name = fct_inorder(Name))  
                  
                  p %>% 
                  ggplot() +
                  aes(x = Name,
                      y = value,
                      fill = variable) +
                  geom_bar(position = "fill",
                           stat = "summary") +
                  geom_text(data = long_totals,
                            aes(y = 100,
                                x = Name,
                                label = Total),
                            size = 7,
                            position = position_fill(vjust = 1.02)) +
                  scale_y_continuous(labels = scales::percent_format())

Also, I am plotting total numbers using geom_text

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 :

Add the proportion c by group like this, when generating p:

... %>%
  group_by(Name) %>% 
  mutate(prop_c = sum(value[variable=="c"], na.rm=T)/sum(value, na.rm=T))

Then plot, using reorder:

ggplot() +
  geom_col(data= p,aes(x = reorder(Name,prop_c, decreasing=T),y = value,fill = variable),position = "fill") + 
  geom_text(data = long_totals, aes(y = 100,x = Name,label = Total),size = 7,position = position_fill(vjust = 1.02)) +
  scale_y_continuous(labels = scales::percent_format())

reorder_c

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