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

如何使用ggplot绘制Y轴为百分比的barplot统计肾病分类死亡概率

实现百分比Y轴条形图(ggplot方案)

第一步:分组计算死亡率

首先基于你已有的预处理逻辑,按分组维度统计每组的死亡占比,你需要的8个条形对应8个分组统计结果,计算逻辑完全匹配你给出的死亡率规则:

# 加载依赖包
library(survival)
library(tidyverse)

# 预处理标记存活状态
kidney$mortality <- ifelse(kidney$status == 1, "Dead", "Alive")

# 按疾病、性别分组统计死亡率,得到8行结果对应8个条形
death_stat <- kidney %>%
  group_by(disease, sex) %>%
  summarise(
    total_cnt = n(),
    dead_cnt = sum(status == 1),
    death_pct = dead_cnt / total_cnt * 100,
    .groups = "drop"
  )

运行后你可以查看death_stat表,其中disease为other的对应分组death_pct值为100,完全符合你的要求。

第二步:ggplot绘制条形图

使用geom_col绘制条形,设置Y轴为百分比格式:

ggplot(death_stat, 
       aes(x = as.factor(disease), 
           y = death_pct, 
           fill = as.factor(sex))) +
  # 并列展示条形,避免重叠,刚好每个疾病下2个性别共8个条形
  geom_col(position = position_dodge(0.9), width = 0.8) +
  # Y轴设置为百分比展示,上限留余量显示数值标签
  scale_y_continuous(labels = ~ paste0(.x, "%"), limits = c(0, 110)) +
  # 添加百分比数值标签
  geom_text(aes(label = paste0(round(death_pct, 1), "%")),
            position = position_dodge(0.9), vjust = -0.2, size = 3.5) +
  # 自定义坐标轴和图例标题
  labs(x = "疾病类型", y = "死亡率", fill = "性别") +
  theme_bw()

如果不需要按性别并列展示,只需要调整aes的分组映射即可,统计逻辑不需要修改。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:00:01