如何在ggplot2柱状图中按孵化质量从小到大排列X轴
解决ggplot2柱状图X轴排序混乱问题
你的柱状图X轴(孵化前体重区间)排列混乱,核心原因是last_rank列大概率为字符类型,ggplot默认按字符字典序排序,而非数值逻辑顺序。以下是两种可行的修复方案:
方案1:提前将last_rank转为有序因子(推荐)
在数据处理流程中,先提取每个区间的起始数值,按数值大小排序后将last_rank设为有序因子,确保绘图时X轴按正确逻辑排列:
H <- read.csv("H.csv") library("ggplot2") library(dplyr) library(tidyr) # 提取区间起始值,排序后生成因子水平列表 sorted_ranks <- H %>% drop_na(last_rank) %>% distinct(last_rank) %>% mutate(start_num = as.numeric(sub("-.*", "", last_rank))) %>% arrange(start_num) %>% pull(last_rank) H %>% drop_na(last_rank) %>% filter(chick_outcome %in% c("Released", "Died")) %>% count(last_rank, chick_outcome) %>% group_by(last_rank) %>% mutate(n = n/sum(n) * 100) %>% # 将last_rank转为有序因子,绑定排序后的水平 mutate(last_rank = factor(last_rank, levels = sorted_ranks, ordered = TRUE)) %>% ggplot() + aes(last_rank, n, fill = chick_outcome, label = paste0(round(n,2), "%")) + geom_col(position = 'stack') + # 注:geom_col是geom_bar(stat='identity')的简写,二者保留一个即可 theme(axis.text.x = element_text(angle = 45, hjust = 0.9)) + geom_text(position = position_stack(0.5)) + labs(title = "孵化前体重对雏鸟存活结果的影响", x = "孵化前体重区间(g)", y = "结果占比(%)") + scale_fill_manual(values = c("red", "green"), name = "雏鸟结果") + theme_classic() + theme(plot.title = element_text(hjust = 0.5, size = 17, family = "Times new roman"))
方案2:在ggplot的aes中直接指定X轴顺序
如果不想修改数据类型,可在aes中用reorder()函数直接指定排序逻辑(按区间起始数值排序):
H <- read.csv("H.csv") library("ggplot2") library(dplyr) library(tidyr) H %>% drop_na(last_rank) %>% filter(chick_outcome %in% c("Released", "Died")) %>% count(last_rank, chick_outcome) %>% group_by(last_rank) %>% mutate(n = n/sum(n) * 100) %>% ggplot() + # 用reorder指定last_rank按区间起始数值排序 aes(x = reorder(last_rank, as.numeric(sub("-.*", "", last_rank))), y = n, fill = chick_outcome, label = paste0(round(n,2), "%")) + geom_col(position = 'stack') + theme(axis.text.x = element_text(angle = 45, hjust = 0.9)) + geom_text(position = position_stack(0.5)) + labs(title = "孵化前体重对雏鸟存活结果的影响", x = "孵化前体重区间(g)", y = "结果占比(%)") + scale_fill_manual(values = c("red", "green"), name = "雏鸟结果") + theme_classic() + theme(plot.title = element_text(hjust = 0.5, size = 17, family = "Times new roman"))
额外优化提示
原代码中geom_bar(position = 'stack', stat = 'identity')与geom_col()功能完全重复,保留其中一个即可。
内容的提问来源于stack exchange,提问作者Jana Rau
相关产品推荐
相关产品推荐

