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

如何在R的geom_density图中将Y轴改为百分比(分年对比)

解决方法:将geom_density的Y轴改为按年份的百分比占比

方法一:直接修改ggplot代码(无需预处理数据)

这是最简单的方式,利用ggplot的after_stat函数将概率密度转换为百分比,确保每个年份的曲线下总面积为100%,彻底消除年度手术总量差异的影响:

library(ggplot2)

ggplot(Ingrepen9, aes(x = LeeftijdBijOK, colour = Operatiejaar)) +
  # 将密度值乘以100转换为百分比
  geom_density(aes(y = after_stat(density * 100)), show.legend = TRUE) +
  ggtitle(
    label = "Verdeling leeftijden van patiënten",
    subtitle = "Percentage per operatiejaar uit het WKZ") +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)) +
  xlab("Leeftijd bij operatie") +
  ylab("Percentage van patiënten per jaar") +
  xlim(0, 60) +
  scale_color_brewer(palette = "Set1")

方法二:预处理数据后绘制(适用于需要自定义密度计算的场景)

如果坚持要先预处理数据,需按年份分组计算年龄的密度估计值,再转换为百分比:

library(dplyr)
library(ggplot2)
library(tidyr)

# 按年份分组计算密度估计
Ingrepen9_density <- Ingrepen9 %>%
  group_by(Operatiejaar) %>%
  summarise(
    # 计算密度,指定x轴范围与原图一致
    dens = list(density(LeeftijdBijOK, from = 0, to = 60)),
    .groups = "drop"
  ) %>%
  # 展开密度结果的x和y值
  unnest_wider(dens) %>%
  unnest(cols = c(x, y)) %>%
  # 转换为百分比
  mutate(percentage = y * 100)

# 绘制曲线
ggplot(Ingrepen9_density, aes(x = x, y = percentage, colour = Operatiejaar)) +
  geom_line() +
  ggtitle(
    label = "Verdeling leeftijden van patiënten",
    subtitle = "Percentage per operatiejaar uit het WKZ") +
  theme(
    plot.title = element_text(hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5)) +
  xlab("Leeftijd bij operatie") +
  ylab("Percentage van patiënten per jaar") +
  xlim(0, 60) +
  scale_color_brewer(palette = "Set1")

你之前的代码问题说明

  1. 参数错误:原代码中aes里的cut=Operatiejaar是无效参数,colour=Operatiejaar已经会自动按年份分组,无需额外设置。
  2. 预处理逻辑偏差:你之前的汇总代码计算的是每个年龄在当年的离散占比,但geom_density需要的是连续的密度估计值,直接用离散占比无法生成正确的密度曲线,因此会失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:40:33