使用purrr批量生成ggplot2图表时如何自定义facet_grid标签
错误原因
labeller参数不支持直接传入paste0拼接的表达式,它需要接收符合ggplot2规范的标签处理函数- 原有代码中
group_n的统计逻辑是「分组变量+目标题项」双维度的样本量,不符合分面标签需要的「单分组维度总样本量」需求,同时占比计算的分母也需要对应调整为分组总样本量。
修改后的完整可运行代码
library(purrr) library(dplyr) library(ggplot2) library(tidyr) # 原始数据集不变 test <- tibble(s1 = c("Agree", "Neutral", "Strongly disagree"), s2rl = c("Agree", "Neutral", NA), f1 = c("Strongly agree", NA, "Strongly disagree"), f2rl = c(NA, "Disagree", "Strongly disagree"), level = c("Manager", "Employee", "Employee"), location = c("USA", "USA", "AUS")) test_items <- test %>% dplyr::select(s1, s2rl, f1, f2rl) titles <- c("S1 results", "Results for S2RL", "Fiscal Results for F1", "Financial Status of F2RL") group_name <- c("level", "location") # 修改后的绘图函数 facet_plots = function(variable, group, title) { # 总样本量统计不变 total_n <- test %>% summarize(n = sum(!is.na(.data[[variable]]))) # 新增:统计每个分面对应分组的总样本量(单分组维度) group_total_n <- test %>% group_by(.data[[group]]) %>% summarize(n = sum(!is.na(.data[[variable]]))) # 统计每个分组下各题项选项的计数、占比 plot_data <- test %>% count(.data[[group]], .data[[variable]]) %>% left_join(group_total_n, by = group, suffix = c("_item", "_total")) %>% mutate(percent = 100*(n_item / n_total)) %>% drop_na() plot2 <- plot_data %>% ggplot(aes(x = .data[[variable]], y = percent, fill = .data[[variable]])) + geom_bar(stat = "identity") + geom_text(aes(label= paste0(round(percent, 1), "%"), fontface = "bold", family = "Arial", size=14), vjust= 0, hjust = -.5) + ylab("\nPercentage") + labs( title = title, subtitle = paste0("(总N = ", total_n$n, ")") ) + coord_flip() + theme_minimal() + ylim(0, 100) + # 修正labeller逻辑 facet_grid(~.data[[group]], labeller = as_labeller(function(x) { paste0(x, " (N = ", group_total_n$n[match(x, group_total_n[[group]])], ")") })) return(list(plot2)) } # 批量调用不变 my_plots <- expand_grid(tibble(item = names(test_items), title=titles), group = group_name) %>% pmap(function(item, group, title) facet_plots(item, group, title)) # 查看生成的图表,例如第一个图表 my_plots[[1]]
核心修改说明
- 新增
group_total_n统计每个分组维度的总样本量,同时修正了占比计算的分母逻辑,避免占比计算错误 - 用
as_labeller自定义标签处理函数,匹配每个分组名对应的样本量后拼接成要求的分组名 (N = 数值)格式,适配facet_grid的参数要求
内容的提问来源于stack exchange,提问作者J.Sabree
相关产品推荐
相关产品推荐

