按 R 中的比例或百分比对堆叠条形图进行排序

Order the stacked barplot by proportion or percent in R

我可以根据数量而不是比例对我的地块进行排序。我想按“c”的比例排列 x 轴上的条形图。这是我的代码

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

此外,我正在使用 geom_text

绘制总数

像这样按组添加比例c,生成的时候p:

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

然后绘制,使用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())