如何在ggplot分组计数条形图中按Depth组显示百分比?
问题描述
我现有如下代码:
tbl <- with(mydata, table(Species, Depth)) library(ggplot2) ggplot(as.data.frame(tbl), aes(factor(Depth), Freq, fill = Species)) + geom_col(position = 'dodge')
以及如下数据框:
Site Depth Substrate PoePres HaliPres Species 1 2 0.5 Sand 0 1 DMonte 2 2 0.5 Sand 0 1 DMonte 3 2 0.5 Sand 0 1 DMonte 4 2 0.5 Sand 0 1 DMonte 5 2 0.5 Sand 0 1 DMonte 6 2 0.5 Sand 0 1 DSandi 7 2 0.5 Sand 0 1 DSandi 8 2 0.5 Sand 0 1 DSandi 9 7 0.6 Sand 0 1 DMonte 10 7 0.6 Sand 0 1 DMonte 11 7 0.6 Sand 0 1 DMonte
希望将当前按计数展示的条形图,改为按Depth组显示百分比,该如何实现?
解决方案
这里提供两种实用的实现方式:
方法一:先手动计算组内百分比(数据透明,易调整)
用dplyr分组计算每个Depth组内各Species的占比,再绘图:
library(ggplot2) library(dplyr) # 计算每个Depth组内的百分比 mydata_percent <- mydata %>% group_by(Depth) %>% count(Species) %>% # 统计每个Depth下各Species的数量 mutate(percent = n / sum(n) * 100) # 计算百分比 # 绘制分组百分比条形图 ggplot(mydata_percent, aes(x = factor(Depth), y = percent, fill = Species)) + geom_col(position = "dodge") + # 条形并列展示 labs(y = "百分比(%)") # 自定义y轴标签
方法二:直接在ggplot中自动计算百分比(代码简洁)
利用after_stat()和group参数,让ggplot自动计算组内占比:
library(ggplot2) library(scales) ggplot(mydata, aes(x = factor(Depth), fill = Species)) + geom_col(aes(y = after_stat(prop), group = Depth), position = "dodge") + labs(y = "百分比(%)") + scale_y_continuous(labels = percent_format()) # 将小数转为百分比格式显示
说明
- 两种方法都能实现按Depth组展示Species的百分比,方法一适合需要查看中间计算结果的场景,方法二更简洁高效。
position = "dodge"保证同一Depth下的不同Species条形并列展示,若想堆叠展示百分比,可将其改为position = "fill"。
内容的提问来源于stack exchange,提问作者Lili
相关产品推荐
相关产品推荐

