如何在ggplot中按总值及complete子集值对堆叠柱状图排序?
问题:调整柱状图的排序规则
我创建了如下柱状图:
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")
当前图表已按total值降序排列,但我希望同时按complete类别的value值降序排列,最终id顺序为1,2,4,3,5,该如何实现?
解决方案
要实现先按total降序,再按complete类别对应的value降序排列,可通过以下两种方式修改代码:
方式一:预处理数据添加排序依据
先为每个id提取对应的complete类别值,再将total和complete_value组合作为排序键:
library(dplyr) library(ggplot2) 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)) # 为每个id添加complete类别的value值 mydata <- mydata %>% group_by(id) %>% mutate(complete_value = value[category == "complete"]) %>% ungroup() mydata %>% ggplot(aes(x=reorder(id, desc(paste(total, complete_value, sep = "_"))), 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")
方式二:直接定义因子顺序
先筛选出complete类别的数据,按规则排序后提取id顺序,再将原数据的id转换为对应顺序的因子:
library(dplyr) library(ggplot2) 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)) # 生成排序后的id列表 sorted_ids <- mydata %>% filter(category == "complete") %>% arrange(desc(total), desc(value)) %>% pull(id) # 将id转换为指定顺序的因子 mydata$id <- factor(mydata$id, levels = sorted_ids) mydata %>% ggplot(aes(x=id, 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")
两种方式都能让id按1,2,4,3,5的顺序排列,优先满足total降序,当total相同时,按complete类别的value降序排列。
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

