如何在ggplot2的geom_bar中按指定顺序排列条形?
解决ggplot2条形图自定义顺序问题
问题出在Patient列默认是字符类型,ggplot2会按字母顺序排序。要实现自定义顺序,需要将该列转换为**因子(factor)**并明确指定层级顺序——reorder函数是基于数值变量的统计量排序,不适合固定自定义顺序,所以之前尝试无效。
修改后的完整代码:
library(readr) library(ggplot2) # 读取数据 ave_gini_and_shannon_timepoint_groups <- read_csv("~//.R/ave gini and shannon timepoint groups.csv") # 将Patient转换为因子,指定自定义顺序 ave_gini_and_shannon_timepoint_groups$Patient <- factor( ave_gini_and_shannon_timepoint_groups$Patient, levels = c("pre", "1 to 3", "4 to 6", "7 to 9", "10 to 12", "13 to 18", "19 to 24", "24+") ) # 绘图 ggplot(ave_gini_and_shannon_timepoint_groups, aes(x=Patient, fill=Patient, y=Shannon_T)) + geom_bar(stat = "identity", width=0.4) + scale_fill_hue(c = 40) + theme(legend.position="none")
关键说明
- 因子的
levels参数严格按照你需要的顺序设置,ggplot2会以此为依据排列条形 - 如果后续需要调整顺序,只需修改
levels向量中的元素顺序即可
内容的提问来源于stack exchange,提问作者Ellie
相关产品推荐
相关产品推荐

