如何在马赛克图(Mosaic Plot)的每个方块上方添加百分比标签
解决马赛克图百分比标签不显示问题
你遇到的问题是geom_text无法正确生成百分比标签,核心原因:
ggmosaic的stat_mosaic不会自动生成percent统计变量,原代码里的after_stat(percent)找不到对应数据- 百分比格式化的用法有误,
format不属于geom_text参数,应直接在标签中调用格式化函数
以下是两种可行的修正方案:
方案一:使用预计算的百分比数据
你已经提前计算了每个分组的百分比,可直接将该数据集传入geom_text,匹配分组变量定位标签:
library(palmerpenguins) library(dplyr) library(ggplot2) library(ggmosaic) library(scales) # 预计算各分组百分比 pen_perc <- penguins %>% count(island, sex) %>% group_by(island) %>% mutate(percent = n / sum(n)) # 绘制带标签的马赛克图 ggplot(data = penguins) + geom_mosaic(aes(x = product(sex, island), fill = island, weight = 1)) + geom_text( data = pen_perc, aes( x = product(sex, island), label = percent(percent, accuracy = 0.1), weight = 1 ), stat = "mosaic", aes(x = after_stat(xcenter), y = after_stat(ycenter)) )
方案二:直接在统计层计算百分比
无需预计算,利用stat_mosaic生成的prop统计变量直接计算并格式化百分比:
library(palmerpenguins) library(ggplot2) library(ggmosaic) library(scales) ggplot(data = penguins) + geom_mosaic(aes(x = product(sex, island), fill = island, weight = 1)) + geom_text( aes( x = after_stat(xcenter), y = after_stat(ycenter), label = percent(after_stat(prop), accuracy = 0.1) ), stat = "mosaic", aes(weight = 1) )
关键说明
- 两种方案都需确保
geom_text的stat="mosaic",通过after_stat(xcenter)和after_stat(ycenter)获取马赛克块中心位置 - 方案一需给
geom_text传入预计算的pen_perc数据集,同时匹配x分组变量与weight参数 - 方案二直接使用
stat_mosaic生成的prop变量(代表分组比例),用scales::percent格式化显示
内容的提问来源于stack exchange,提问作者V_Shih_0614
相关产品推荐
相关产品推荐

