Home > Enterprise >  Order the stacked barplot by proportion or percent in R
Order the stacked barplot by proportion or percent in R

Time:05-19

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

CodePudding user response:

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

  • Related