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

基于R语言:筛选特定受试者及绘制band plot的技术咨询

R语言问题解决方案:筛选特定受试者及绘制占比Band Plot

1. 筛选同时记录stomachache和reflux事件的受试者

先构造示例数据集,再通过分组筛选出同时拥有两类事件的受试者:

library(dplyr)

# 构造示例数据集
df <- tibble(
  Subject_ID = c("A21", "A21", "A21", "A22", "A22", "A23", "A23", "A24"),
  event = c("stomachache", "eating disorder", "reflux", "stomachache", "muscle pain", "stomachache", "reflux", "eating disorder"),
  Week = c(23, 10, 21, 15, 9, 21, 12, 16),
  Grade = c(3, 2, 1, 2, 2, 1, 3, 2)
)

# 筛选同时存在stomachache和reflux的受试者
target_subjects <- df %>%
  group_by(Subject_ID) %>%
  filter(all(c("stomachache", "reflux") %in% event)) %>%
  ungroup() %>%
  distinct(Subject_ID)

# 输出结果
target_subjects

运行后会得到符合条件的受试者ID:A21和A23。

2. 绘制Band Plot展示两类事件共存的受试者占比

使用ggplot2绘制带置信区间的Band Plot(对应你需要复刻的图类型),步骤如下:

第一步:整理数据,计算占比

# 标记每个受试者是否同时具备两类事件
subject_status <- df %>%
  group_by(Subject_ID) %>%
  summarise(has_both = all(c("stomachache", "reflux") %in% event)) %>%
  ungroup()

# 按周统计占比(若需整体占比,直接用mean(subject_status$has_both)即可)
weekly_ratio <- df %>%
  left_join(subject_status, by = "Subject_ID") %>%
  group_by(Week) %>%
  summarise(
    total_subjects = n_distinct(Subject_ID),
    both_subjects = n_distinct(Subject_ID[has_both]),
    ratio = both_subjects / total_subjects
  ) %>%
  ungroup()

第二步:绘制Band Plot

library(ggplot2)
library(scales)

ggplot(weekly_ratio, aes(x = Week, y = ratio)) +
  # 绘制置信区间带(示例用±10%模拟,实际可通过统计方法计算真实置信区间)
  geom_ribbon(aes(ymin = pmax(0, ratio - 0.1), ymax = pmin(1, ratio + 0.1)), 
              fill = "#63B8FF", alpha = 0.3) +
  # 绘制占比折线
  geom_line(color = "#104E8B", size = 1) +
  # 绘制数据点
  geom_point(color = "#104E8B", size = 2) +
  # 将y轴转为百分比格式
  scale_y_continuous(labels = percent_format(accuracy = 1)) +
  # 设置标签和主题
  labs(
    x = "周数",
    y = "同时存在两类事件的受试者占比",
    title = "不同周数下两类事件共存受试者占比"
  ) +
  theme_minimal()

该图会展示各周内同时存在两类事件的受试者占比,蓝色带为置信区间范围,折线为占比趋势。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:48:36