如何在ggplot中按总值和子集值对堆积条形图进行排序?

问题描述 投票:0回答:1

我创建了如下的条形字符:

mydata<-data.frame(id=c(1,1,2,2,3,3,4,4,5,5),
                   total=c(24,24,24,24,22,22,22,22,22,22),
                   category=rep(c("uncomplete","complete"),5),
                   value=c(0,24,0,24,1,21,0,22,2,20))

mydata%>%
  ggplot(aes(x=reorder(id, -total),
             y=value, fill=factor(category,levels=c("uncomplete","complete"))))+
  geom_bar(position=position_stack(),stat="identity",width=0.7) + 
  geom_text(data=subset(mydata,value != 0),
            aes(label = value),position=position_stack(vjust=0.5),size=3) +
  theme(legend.position = c(0.90,0.85)) +
  labs(x="Site ID",y="",fill="") +  
  scale_y_continuous(breaks = seq (0, 30, 5), limits=c(0,30), name="Enrollment")

enter image description here

如您所见,图表按

total
数字降序排列。但是,我不知道如何让图表同时按
complete
数字降序排序,即我想将id排序为1,2,4,3,5。

r ggplot2 bar-chart
1个回答
0
投票

考虑

dplyr::arrange
+
forcats::fct_inorder

mydata |> 
    arrange(desc(total), desc(value)) |> 
    mutate(id = forcats::fct_inorder(as.character(id))) |>
    [...]

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.