R中手动排序并重命名geom_bar堆叠条形图
问题描述
在使用R绘制geom_bar堆叠条形图时,需实现以下需求:
- 聚类分析得到k=1-3的簇分配,但簇数字标签顺序不符合预期:Cluster A对应1,Cluster B对应3,Cluster C对应2
- 手动控制条形图顺序,让1、3、2分别对应Cluster A、B、C,同时X的填充顺序匹配簇内的堆叠逻辑
用户提供的模拟数据及尝试代码如下:
#LIBRARIES library(viridis) library(ggplot2) library(hrbrthemes) #MOCK DATA X <- sample(seq(from = 0, to = 5, by = 1), size = 50, replace = TRUE) Cluster <- sample(seq(from = 1, to = 3, by = 1), size = 50, replace = TRUE) DAT %>% mutate(Cluster = case_when(X < 2 ~ "1", X <4 ~ "3", X <6 ~ "2")) X <- as.factor(X) DAT <- data.frame(X, Cluster) #EXISTING CODE ATTEMPT ggplot(DAT, aes(x= Cluster, fill = X), color = "X") + geom_bar(position = position_fill(reverse = TRUE), stat="count", width = 0.80) + theme_ipsum(axis = TRUE, grid = FALSE, axis_col = "black", base_size = 9) + theme(plot.title = element_text(hjust = 0.5, size = 9, face = "bold"), axis.text = element_text(size = 9)) + scale_fill_viridis_d(option = "G")+ (scale_x_reverse(breaks = c(1:3), labels = paste("Cluster", LETTERS[1:3])))+ coord_flip() + xlab("")
期望效果:
解决方案
核心通过设置因子水平顺序控制条形图和填充逻辑,以下是修正后的完整代码:
# 加载依赖包 library(viridis) library(ggplot2) library(hrbrthemes) library(dplyr) # 生成可复现的模拟数据 set.seed(123) X <- sample(seq(from = 0, to = 5, by = 1), size = 50, replace = TRUE) DAT <- data.frame(X) %>% mutate(Cluster = case_when( X < 2 ~ "1", X < 4 ~ "3", X < 6 ~ "2" )) %>% # 强制指定Cluster的显示顺序为1→3→2,X按0-5的自然顺序排列 mutate( Cluster = factor(Cluster, levels = c("1", "3", "2")), X = factor(X, levels = as.character(0:5)) ) # 绘制堆叠条形图 ggplot(DAT, aes(x = Cluster, fill = X)) + geom_bar(position = position_fill(reverse = FALSE), stat = "count", width = 0.80) + # 为Cluster设置对应标签 scale_x_discrete(labels = c("Cluster A", "Cluster B", "Cluster C")) + # 确保填充色顺序匹配X的因子顺序 scale_fill_viridis_d(option = "G", breaks = levels(DAT$X)) + theme_ipsum(axis = TRUE, grid = FALSE, axis_col = "black", base_size = 9) + theme( plot.title = element_text(hjust = 0.5, size = 9, face = "bold"), axis.text = element_text(size = 9) ) + coord_flip() + xlab("")
关键调整说明
- Cluster顺序控制:用
factor(Cluster, levels = c("1", "3", "2"))直接定义条形图的排列顺序,替换原代码中错误的scale_x_reverse(Cluster是离散因子,非连续变量) - X填充顺序匹配:将X转换为有序因子,再通过
scale_fill_viridis_d的breaks参数绑定填充色顺序,保证堆叠逻辑和类别顺序一致 - 数据修正:修复原代码中
DAT未定义就调用mutate的错误,用链式语法简化数据生成流程 - 堆叠方向调整:将
position_fill(reverse = TRUE)改为reverse = FALSE,让X的堆叠顺序和因子顺序对齐(可根据实际需求反向)
内容的提问来源于stack exchange,提问作者EB3112
相关产品推荐
相关产品推荐

