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

如何在R的ggplot直方图中将Y轴从观测计数改为百分比?

调整PRS直方图Y轴为组内占比(解决样本量差异问题)

问题背景

我用以下代码绘制病例组(编码1)和对照组(编码0)的PRS多基因风险评分直方图,但两组样本量差异极大(对照组远多于病例组),当前Y轴是个体数量,导致病例组直方图高度极低,没法观察分布差异。希望把Y轴改成各组内对应评分的个体占比,让两组直方图高度一致。

原绘图代码:

histogram_endo_cases_controls <- ggplot(prs_data, aes(x = normalized, fill = as.factor(endometriosis))) +
  geom_histogram(position = "identity", alpha = 0.5, binwidth = 0.2, color = "black") +
  scale_fill_manual(values = c("blue", "yellow"), 
                    labels = c("Controls", "Cases"),
                    name = "Group") +
  labs(title = "Histogram of Polygenic Risk Scores",
       x = "PRS",
       y = "Frequency") +
  theme_minimal()

示例数据:
所有数据:

data_all <- data.frame(
  x = c(0.00, -0.54, 1.35, 1.23, -2.34),
  y = c(304000, 100500, 50300, 55400, 12)
)

仅病例组:

data_cases <- data.frame(
  x = c(0.00, -0.54, 1.35, 1.23, -2.34),
  y = c(4000, 500, 300, 400, 2)
)

仅对照组:

data_controls <- data.frame(
  x = c(0.00, -0.54, 1.35, 1.23, -2.34),
  y = c(300000, 100000, 50000, 55000, 10)
)

解决方案

只需修改geom_histogram的Y轴映射,用ggplot的统计变换函数计算组内占比/密度,两种方式可选:

方式1:用密度值(推荐,保证每组总面积为1)

修改后的代码:

histogram_endo_cases_controls <- ggplot(prs_data, aes(x = normalized, fill = as.factor(endometriosis))) +
  # 用after_stat(density)将Y轴转为组内密度
  geom_histogram(aes(y = after_stat(density)), 
                 position = "identity", alpha = 0.5, binwidth = 0.2, color = "black") +
  scale_fill_manual(values = c("blue", "yellow"), 
                    labels = c("Controls", "Cases"),
                    name = "Group") +
  labs(title = "Histogram of Polygenic Risk Scores (Group-wise Density)",
       x = "PRS",
       y = "Density (Proportion within Group)") +
  theme_minimal()

方式2:直接显示组内占比(0-1范围)

如果想直观看到百分比,用count / sum(count)计算每组内的占比:

histogram_endo_cases_controls <- ggplot(prs_data, aes(x = normalized, fill = as.factor(endometriosis))) +
  geom_histogram(aes(y = after_stat(count / sum(count))), 
                 position = "identity", alpha = 0.5, binwidth = 0.2, color = "black") +
  scale_fill_manual(values = c("blue", "yellow"), 
                    labels = c("Controls", "Cases"),
                    name = "Group") +
  labs(title = "Histogram of Polygenic Risk Scores (Group-wise Proportion)",
       x = "PRS",
       y = "Proportion within Group") +
  theme_minimal()

说明

两种方式都会自动按endometriosis分组计算,不管两组样本量差异多大,直方图的高度范围一致,能清晰对比PRS的分布差异。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:29:58