如何为ggplot分面图的单个分组补全缺失值?
分面柱状图对齐实现方法
原始代码与问题
你的原始R代码如下:
df <- data.frame(percent=c(3, 5, 2), method=c("A", "A", "B"), ancestry=c("European", "African", 'African'), pair=c('pair one', 'pair two','pair two')) p1 <- ggplot(data=df, aes(x=pair, y=percent, fill=ancestry)) + geom_bar(stat="identity", position=position_dodge()) + facet_wrap(~ method) p1 <- p1 + geom_text(aes(label=percent), position=position_dodge(width=0.9))
当前生成的图存在问题:method B的分面中,pair two只有African的柱子,而method A的分面中每个pair都有European和African两种柱子,导致两个分面的x轴柱子宽度、位置无法对齐。你期望的效果是两个分面的x轴元素完全对齐,method B的pair two位置保留European的占位柱子(高度为0)。
简便实现方法
核心思路是补全数据中所有method、pair、ancestry的组合,缺失的percent值填充为0,这样ggplot会自动绘制所有柱子(包括高度为0的),实现分面间的对齐。
修改后的代码如下:
library(tidyr) library(ggplot2) # 补全所有变量组合,缺失的percent设为0 df_complete <- df %>% complete(method, pair, ancestry, fill = list(percent = 0)) # 绘图,仅显示非0数值的标签 p1 <- ggplot(data=df_complete, aes(x=pair, y=percent, fill=ancestry)) + geom_bar(stat="identity", position=position_dodge()) + facet_wrap(~ method) + geom_text(aes(label=ifelse(percent > 0, percent, "")), position=position_dodge(width=0.9))
这样生成的图就会和你期望的效果一致:两个分面的x轴柱子完全对齐,method B中European的柱子高度为0且不显示标签。
内容的提问来源于stack exchange,提问作者curious
相关产品推荐
相关产品推荐

