You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ggplot2绘制分组相对频率柱状图?

分组相对频率柱状图实现方案(ggplot2)

问题背景

两组文本论点数量对比,因样本量差异,需展示每组内论点数量的相对频率,而非绝对计数,避免手动计算频率的繁琐。

示例数据:

df <- data.frame(c("A","A","A","B","B","B","B","B","B"),c(1,1,2,0,1,1,1,2,2))
colnames(df) = c("group","count")

原代码生成绝对计数柱状图,不符合需求:

ggplot(df,aes(fill=group,x=count)) + geom_bar(position="dodge")

方案一:用dplyr预处理计算相对频率

借助tidyverse的dplyr工具自动按组计算相对频率,无需手动统计:

library(dplyr)
library(ggplot2)

# 按group分组,计算每组内各count的相对频率
df_freq <- df %>%
  group_by(group) %>%
  count(count) %>%
  mutate(relFreq = n / sum(n)) %>%
  ungroup()

# 绘制分组相对频率柱状图
ggplot(df_freq, aes(x = factor(count), y = relFreq, fill = group)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(x = "论点数量", y = "相对频率") +
  scale_y_continuous(labels = scales::percent) # 可选:将y轴转为百分比显示
  • group_by(group)指定按组计算范围
  • count(count)统计每组内各论点数量的出现次数
  • mutate(relFreq = n / sum(n))计算每组内的相对频率
  • x = factor(count)确保x轴为离散型,解决连续轴问题

方案二:直接在ggplot中实现(无需预处理)

通过调整geom_bar的统计变换逻辑,直接生成相对频率:

library(ggplot2)

ggplot(df, aes(x = factor(count), fill = group)) +
  geom_bar(aes(y = after_stat(count / sum(count))), 
           position = "dodge", 
           stat = "count") +
  labs(x = "论点数量", y = "相对频率") +
  scale_y_continuous(labels = scales::percent)
  • after_stat(count / sum(count)):利用ggplot的统计变换,在完成每组计数后,自动计算组内相对频率
  • stat = "count"保留计数逻辑,再通过after_stat转换为比例
  • factor(count)强制x轴为离散型,避免连续轴问题

内容的提问来源于stack exchange,提问作者paboe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 06:33:27