R语言堆叠条形图添加列百分比频率及修改Y轴为百分比实现方案
实现方案
首先确保你已经加载了所需依赖包:
library(ggplot2) library(scales) # 用于百分比格式化
1. Y轴改为组内百分比(适配对比不同种族分布的需求)
只需修改geom_bar的position参数为fill,再调整Y轴刻度为百分比格式即可,改动仅需在你原有代码基础上新增2行:
p <- ggplot(data = Data, mapping = aes(x = race, fill = pcr)) p + geom_bar(position = "fill") + scale_y_continuous(labels = percent_format()) + # 把Y轴数值转为百分比显示 labs(y = "组内占比")
这个方案会自动把每个种族分组的总高度设为1(即100%),不同种族的阳性/阴性占比会直接对齐,分布相似度一眼就能看出来。
2. 给每个分段添加居中百分比标注
在上述代码基础上新增geom_text层即可,标签会自动显示在对应分段的居中位置:
p <- ggplot(data = Data, mapping = aes(x = race, fill = pcr)) p + geom_bar(position = "fill") + geom_text(aes(label = percent(..count.. / tapply(..count.., ..x.., sum)[..x..], accuracy = 0.1)), stat = "count", position = position_fill(vjust = 0.5)) + scale_y_continuous(labels = percent_format()) + labs(y = "组内占比")
如果需要调整百分比的小数位数,修改percent()函数里的accuracy参数即可,比如accuracy = 1就是只显示整数百分比。
补充说明
如果需要保留计数Y轴,仅添加百分比标签,把代码里所有position = "fill"、position_fill改回默认的position = "stack"、position_stack即可。
内容的提问来源于stack exchange,提问作者keherder
相关产品推荐
相关产品推荐

