R语言绘制双时间帧多水平变量并排百分比柱状图的实现问题
并排百分比柱状图的问题修正
原代码的核心错误点
- 全局双table相除的逻辑存在对齐漏洞:
table(非0计数) / table(全量计数)的计算方式没有严格按「波次+指标名」的分组键绑定结果,两个频次表的因子顺序一旦不匹配,计算出的占比就会和对应的分组错位。 - 硬编码截取字段的逻辑鲁棒性差:通过
substr从拼接字符串里拆分wave和指标名的方式,一旦某个分组在非0计数表里缺失,就会导致Var1字段的顺序和实际计算的占比不对应,最终出现每个x轴分类下仅显示单根柱子的异常。
修正后可直接运行的代码
# 加载依赖包 library(tidyverse) # 原始数据(与你提供的结构完全一致) n <- structure(list(sitime_1 = structure(c(2L, 4L, 1L, 1L, 1L, 1L, 4L, 1L, 4L, 3L, 1L, 4L, 4L, 4L, 1L, 3L, 3L, 3L, 3L, 4L), .Label = c("0", "More than 1 year ago", "Within the past year", "Within the past month" ), class = "factor"), sitime_2 = structure(c(1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 3L, 4L, 1L, 4L, 1L, 1L, 3L, 3L, 3L, 1L ), .Label = c("0", "More than 1 year ago", "Within the past year", "Within the past month"), class = "factor"), sitime_3 = structure(c(1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 3L, 1L, 1L, 1L, 3L, 3L, 4L), .Label = c("0", "More than 1 year ago", "Within the past year", "Within the past month"), class = "factor"), wave = c("secon", "first", "secon", "first", "secon", "first", "secon", "first", "secon", "first", "secon", "first", "secon", "first", "secon", "first", "secon", "first", "secon", "first")), row.names = c(NA, -20L), class = c("data.table", "data.frame")) # 数据长格式转换 + 分组计算非0值占比 n_long <- n %>% pivot_longer(cols = starts_with("si"), names_to = "sit_var") %>% group_by(wave, sit_var) %>% summarise( total_obs = n(), valid_obs = sum(value != "0"), percent = valid_obs / total_obs * 100, .groups = "drop" ) # 绘制多水平并排柱状图 ggplot(n_long, aes(x = sit_var, y = percent, fill = wave)) + geom_bar(stat = "identity", position = position_dodge(0.7), width = 0.6) + labs( x = "sitime 观测序列", y = "非0类别占比 (%)", title = "不同调查波次的sitime指标非0占比对比" ) + scale_y_continuous(limits = c(0, 100)) + theme_bw()
效果说明
运行修正后的代码,每个x轴上的sitime分类下,会并排展示first、secon两个波次的对应占比柱子,完全匹配多水平并排的展示需求。分组计算的逻辑从根源上避免了维度错位、字段拆分错误的问题,不需要依赖硬编码的字符串截取逻辑。
内容的提问来源于stack exchange,提问作者Ali Roghani
相关产品推荐
相关产品推荐

