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

如何使用R语言基于3列数据绘制心脏瓣膜反流程度堆叠柱状图

R语言绘制分组占比堆叠柱状图实操方案

前置依赖安装

你只需要用到tidyverse生态的通用工具包,已安装的话可以跳过安装步骤:

# 首次使用执行安装
install.packages("tidyverse")
# 加载所需工具
library(tidyverse)

步骤1:数据格式转换

你当前的原始数据是宽格式,需要先转成长格式,再统计每个时间点各反流等级的占比:

# ----------------------
# 这部分是模拟你的数据结构,实际使用时替换成你自己的数据源导入代码即可,比如用read.csv()读取本地文件
set.seed(123) # 固定随机数种子方便复现效果
demo_data <- tibble(
  Subject = 1:100,
  trpreop = sample(0:3, 100, replace = T, prob = c(0.1,0.2,0.4,0.3)),
  trpostop = sample(0:3, 100, replace = T, prob = c(0.4,0.3,0.2,0.1)),
  trfollowup = sample(0:3, 100, replace = T, prob = c(0.3,0.4,0.2,0.1))
)
# ----------------------

# 数据清洗与占比计算
plot_data <- demo_data %>%
  # 宽表转长表,保留受试者ID,把三个时间点列转为分组变量
  pivot_longer(cols = -Subject, 
               names_to = "time_point", 
               values_to = "reflux_level") %>%
  # 按时间点、反流等级分组统计样本量
  count(time_point, reflux_level) %>%
  # 按时间点分组,计算每个等级在对应时间点的占比
  group_by(time_point) %>%
  mutate(percent = n / sum(n)) %>%
  ungroup() %>%
  # 修正时间点排序,避免默认按字母乱序
  mutate(time_point = factor(time_point, 
                             levels = c("trpreop", "trpostop", "trfollowup"),
                             labels = c("术前", "术后", "随访")))

步骤2:绘制堆叠占比柱状图

ggplot(plot_data, aes(x = time_point, y = percent, fill = factor(reflux_level, levels = 0:3))) +
  # 绘制堆叠柱,加黑色边框区分色块
  geom_col(position = "stack", color = "black") +
  # Y轴转为百分比显示
  scale_y_continuous(labels = scales::percent_format()) +
  # 调整配色,可自行替换为其他配色方案
  scale_fill_brewer(palette = "Blues", name = "反流严重等级") +
  # 自定义轴标签和标题
  labs(x = "时间节点", y = "人群占比", title = "不同时间点心脏瓣膜反流严重程度分布") +
  # 可选:在每个色块上添加具体占比数值
  geom_text(aes(label = paste0(round(percent*100,1), "%")), 
            position = position_stack(vjust = 0.5), size = 3.5) +
  # 精简主题样式
  theme_minimal()

结果说明

输出的图表会自动生成3根堆叠柱,分别对应术前、术后、随访三个时间节点,每根柱子的色块按0/1/2/3级的严重程度从上到下/从下到上排列,总占比为100%,你可以根据自己的需求调整配色、字体、标签样式等参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:06:01