ggplot2多ID堆叠柱状图绘制求助:按name分组配色
解决ggplot2多ID堆叠柱状图分组配色问题
问题说明
需要绘制包含多个ID的堆叠柱状图,要求:
- 同时展示所有ID的数据
- 按
name分组配色:GroupA使用深浅蓝色系,GroupB使用深浅绿色系
原始数据
df <- tibble::tribble( ~ID, ~Genus, ~name, ~value, "JP", "Dermatophagoides", "GroupA", 0.997, "JP", "Dermatophagoides", "GroupB", NA, "JP", "Dermatophagoides evansi", "GroupA", 0.00259, "JP", "Dermatophagoides evansi", "GroupB", NA, "AM", "Dermatophagoides farinae", "GroupA", 0.302, "AM", "Dermatophagoides farinae", "GroupB", 0.303, "AM", "Dermatopha microceras", "GroupA", 0.650, "AM", "Dermatopha microceras", "GroupB", 0.653, "AM", "N/A", "GroupA", 0.00915, "AM", "N/A", "GroupB", 0.00642, "AS", "Cohorte Bimichaeliina", "GroupA", 0.795, "AS", "Cohorte Bimichaeliina", "GroupB", 0.796, "AS", "Nematalycoidea", "GroupA", 0.0120, "AS", "Nematalycoidea", "GroupB", 0.0123, "AS", "Possibly Cohorte Bimichaeliina", "GroupA", 0.193, "AS", "Possibly Cohorte Bimichaeliina", "GroupB", 0.191 )
修正原始代码错误
你之前的代码中使用select(ID == "JP")是错误的,select用于选择列,筛选行需要用filter:
# 正确筛选单个ID的代码 df1 <- df %>% filter(ID == "JP")
完整解决方案
1. 加载依赖包并预处理数据
首先过滤掉value为NA的行,避免绘图异常:
library(tidyverse) # 数据清洗:移除NA值 df_clean <- df %>% filter(!is.na(value))
2. 构建分组配色映射
根据name为每个Genus分配对应色系的颜色:
# 生成颜色映射:GroupA用深浅蓝色,GroupB用深浅绿色 color_map <- df_clean %>% mutate(color_category = ifelse(name == "GroupA", "blue", "green")) %>% distinct(Genus, color_category) %>% group_by(color_category) %>% # 使用viridis色系生成对应深浅的颜色 mutate(color = case_when( color_category == "blue" ~ scales::viridis_pal(option = "B")(n()), color_category == "green" ~ scales::viridis_pal(option = "G")(n()) )) %>% ungroup() %>% pull(color, Genus)
3. 绘制目标堆叠柱状图
采用分面布局展示GroupA和GroupB,每个分面内按ID展示堆叠柱子:
ggplot(df_clean, aes(x = ID, y = value, fill = Genus)) + # 堆叠柱状图 geom_col(position = "stack", width = 0.8) + # 按name分面,对应两组配色 facet_wrap(~name) + # 应用自定义配色 scale_fill_manual(values = color_map) + # 设置标签 labs( title = "多ID分类堆叠柱状图", x = "样本ID", y = "数值", fill = "属(Genus)" ) + # 优化主题样式 theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.text.x = element_text(angle = 45, hjust = 1), legend.position = "bottom" )
替代布局(同面板展示GroupA/B)
如果希望在同一个面板展示GroupA和GroupB的柱子,可将ID与name组合为x轴:
ggplot(df_clean, aes(x = interaction(ID, name), y = value, fill = Genus)) + geom_col(position = "stack", width = 0.8) + scale_fill_manual(values = color_map) + # 简化x轴标签,只显示ID scale_x_discrete( labels = function(x) stringr::str_split(x, "\\.") %>% purrr::map_chr(1), name = "样本ID" ) + labs( title = "多ID分类堆叠柱状图", y = "数值", fill = "属(Genus)" ) + theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), axis.text.x = element_text(angle = 45, hjust = 1), legend.position = "bottom" )
内容的提问来源于stack exchange,提问作者mashimena
相关产品推荐
相关产品推荐

