如何在ggplot彩色分组柱状图上叠加黑色轮廓预期值柱状图
解决方案
问题1:绘制按迁移类型和聚类划分的黑色轮廓柱状图
直接在geom_bar中写fill=NA会覆盖全局的fill=kmcluster映射,导致分组失效。正确做法是保留全局的fill=kmcluster用于分组,同时将填充色设为完全透明(不影响分组逻辑),并指定黑色边框:
ggplot(expected_data, aes(x = resp_migration_status, y = expected, fill = kmcluster)) + geom_bar( stat = "identity", position = "dodge", color = "black", fill = "transparent" # 用透明填充替代NA,保留分组映射 ) + labs( title = "Expected percentage distribution of network cluster by migration status", x = "Migration Status", y = "Percentage", fill = "Cluster" ) + scale_y_continuous(labels = scales::percent_format(scale = 1)) + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
问题2:叠加轮廓柱状图到原彩色柱状图上
在原彩色柱状图代码基础上,新增一个geom_bar层处理expected数据,核心是保持两层的position和宽度参数一致,确保柱子对齐:
# 原彩色柱状图叠加预期轮廓柱 ggplot(expected_data, aes(x = resp_migration_status, fill = kmcluster)) + # 第一层:实际百分比的彩色柱子 geom_bar( aes(y = percentage), stat = "identity", position = "dodge", width = 0.7 # 统一宽度,保证和轮廓柱对齐 ) + # 第二层:预期分布的黑色轮廓柱子 geom_bar( aes(y = expected), stat = "identity", position = "dodge", color = "black", fill = "transparent", width = 0.7 # 和上层宽度保持一致 ) + labs( title = "Observed vs Expected Percentage Distribution by Migration Status & Cluster", x = "Migration Status", y = "Percentage", fill = "Cluster" ) + scale_y_continuous(labels = scales::percent_format(scale = 1)) + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
关键注意点
- 将
y的映射拆分到每个geom_bar的aes中,避免全局y轴冲突 - 使用
fill="transparent"替代fill=NA,既实现无填充效果,又保留kmcluster的分组逻辑 - 两层的
position="dodge"和width参数必须一致,确保柱子完全对齐
内容的提问来源于stack exchange,提问作者Kristen
相关产品推荐
相关产品推荐

