R语言绘制两种条件共患人群占比柱状图及可拓展函数实现
R可复用实现代码
需提前安装加载tidyverse套件,包含数据处理和绘图所需的dplyr、ggplot2等工具。
plot_cross_cond_pct <- function(df, base_var = "A", target_vars = c("B", "C", "D"), group_by_sex = FALSE, filter_age_gt55 = FALSE) { # 年龄条件筛选 if (filter_age_gt55) { df <- df %>% filter(Age > 55) } # 生成分组变量 group_cols <- c() if (group_by_sex) { group_cols <- c(group_cols, "sex") } # 交叉条件占比计算 stat_df <- df %>% group_by(across(all_of(group_cols))) %>% summarise( total = n(), across(all_of(target_vars), ~ sum(.data[[base_var]] == 1 & .x == 1, na.rm = T)/total * 100, .names = "pct_{.col}") ) %>% pivot_longer(cols = starts_with("pct_"), names_to = "dimension", values_to = "percentage", names_prefix = "pct_") # 绘制柱状图 plot <- ggplot(stat_df, aes(x = dimension, y = percentage)) + geom_col(position = position_dodge2(preserve = "single"), fill = "#2c7fb8", alpha = 0.8) + labs(x = "维度", y = "占比(%)") + theme_bw() # 按性别分组时调整填充映射 if (group_by_sex) { plot <- plot + aes(fill = sex) + scale_fill_brewer(palette = "Set2") } return(plot) }
第一步:导入示例数据
Lines <- "id sex Age A B C D 1 male 90 1 1 0 1 2 female 87 0 1 1 0 3 male 50 1 1 0 0 4 female 54 0 1 0 1" df <- read.table(text = Lines, header = T)
第二步:不同场景调用函数
- 基础场景:无筛选无分组,输出B/C/D三个维度的A&条件占比
plot_cross_cond_pct(df)
- 按性别拆分分组展示
plot_cross_cond_pct(df, group_by_sex = TRUE)
- 仅统计年龄>55的样本
plot_cross_cond_pct(df, filter_age_gt55 = TRUE)
- 扩展多变量场景:如果新增E、F等变量,只需修改
target_vars参数即可
# 新增变量调用示例 # plot_cross_cond_pct(df, target_vars = c("B","C","D","E","F"))
函数特性说明
- 支持任意数量的目标交叉变量,仅需调整
target_vars参数传入对应的变量名向量即可 - 两个分组/筛选参数独立控制,可自由组合使用
- 返回值为标准
ggplot对象,可后续自行调整配色、标签、主题等样式
内容的提问来源于stack exchange,提问作者Economist_Ayahuasca
相关产品推荐
相关产品推荐

