如何为ggplot2的facet_grid面板标题添加唯一triplet_id计数?
问题解决思路与代码修正
你的核心需求是给facet_grid中每个age_group对应的面板标题添加该组唯一triplet_id的数量,原代码的问题主要有两点:
- 直接用
length(unique(triplet_id))会计算整个数据集的唯一ID数,而非当前面板分组的数量; x=5超出了x轴0-1的百分比范围,导致文本完全出现在绘图区域外,无法显示。
下面分两种场景给出解决方案:
场景1:将计数添加到面板标题中
先预处理数据计算每个age_group的唯一ID数量,再自定义标签替换原面板标题:
library(dplyr) library(ggplot2) # 计算每个age_group的唯一triplet_id数量 count_df <- graph %>% group_by(age_group) %>% summarise(unique_count = n_distinct(triplet_id)) %>% ungroup() # 构建带计数的age_group标签 age_labs <- setNames( paste0(count_df$age_group, " (n=", count_df$unique_count, ")"), count_df$age_group ) # 修正后的绘图代码 pl <- ggplot(data = graph,aes(y= Item, fill = Item_score))+ geom_bar(stat="count", position = position_fill(reverse = TRUE), color = "black") + scale_y_discrete(limits=rev)+ scale_fill_manual(values = c("red", "white", "seagreen3"))+ theme_classic() + labs(y ="items", x = "Percentage")+ scale_x_continuous(labels = scales::percent, breaks = seq(0, 1, .25))+ # 使用自定义标签替换原age_group面板标题 facet_grid(visit_type_1~age_group, labeller = labeller(visit_type_1 = time.labs, age_group = age_labs))+ theme(legend.position = "none", text = element_text(size = 30), strip.text.x = element_text(size = 30), strip.text.y = element_text(size = 30), panel.spacing.x=unit(1.5, "lines"), panel.spacing.y=unit(2, "lines"))+ labs(title = "A") pl
场景2:将计数添加到面板内部
如果需要在每个面板的绘图区域内显示计数,需先按facet的分组维度(visit_type_1+age_group)计算数量,再用geom_text添加:
library(dplyr) library(ggplot2) # 按面板分组计算唯一triplet_id数量 panel_counts <- graph %>% group_by(visit_type_1, age_group) %>% summarise(unique_count = n_distinct(triplet_id), .groups = "drop") # 修正后的绘图代码 pl <- ggplot(data = graph,aes(y= Item, fill = Item_score))+ geom_bar(stat="count", position = position_fill(reverse = TRUE), color = "black") + scale_y_discrete(limits=rev)+ scale_fill_manual(values = c("red", "white", "seagreen3"))+ theme_classic() + labs(y ="items", x = "Percentage")+ scale_x_continuous(labels = scales::percent, breaks = seq(0, 1, .25))+ facet_grid(visit_type_1~age_group, labeller = labeller(visit_type_1 = time.labs))+ theme(legend.position = "none", text = element_text(size = 30), strip.text.x = element_text(size = 30), strip.text.y = element_text(size = 30), panel.spacing.x=unit(1.5, "lines"), panel.spacing.y=unit(2, "lines"))+ # 用预处理的分组计数数据添加文本,调整x/y到合适位置 geom_text(data = panel_counts, aes(x = 0.5, y = 1, label = paste0("Count: ", unique_count)), inherit.aes = FALSE, size = 8)+ labs(title = "A") pl
内容的提问来源于stack exchange,提问作者Giorgia
相关产品推荐
相关产品推荐

