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

基于R Tidyverse创建分组堆叠式年龄时间轴

解决方法

1. 模拟数据集(匹配你的数据结构)

先构建和你描述一致的示例数据,方便测试:

set.seed(123)
df <- data.frame(
  ID = 1:20,
  Age = sample(10:80, 20, replace = TRUE),
  gender = sample(c("Male", "Female"), 20, replace = TRUE),
  group = sample(c("disease", "control"), 20, replace = TRUE)
)

2. 数据预处理(实现堆叠与上下分布)

为同组同年龄的样本计算堆叠位置,同时给两组分配正负y值,实现上下分离:

library(dplyr)
df <- df %>%
  group_by(group, Age) %>%
  mutate(stack_pos = row_number()) %>% # 同年龄同组的样本按顺序分配堆叠序号
  ungroup() %>%
  mutate(y = ifelse(group == "disease", stack_pos, -stack_pos)) # disease组在上方,control在下方

3. 绘制符合要求的时间轴图

用ggplot2完成绘图,把x轴放在两组中间,替代原虚线:

library(ggplot2)
ggplot(df, aes(x = Age, y = y)) +
  # 绘制样本点,可按分组和性别区分样式
  geom_point(aes(color = group, shape = gender), size = 3) +
  # 添加ID标签,位置避开点本身
  geom_text(aes(label = ID), 
            vjust = ifelse(df$group == "disease", -0.6, 1.6), 
            size = 2.5, color = "gray20") +
  # 设置时间轴范围为0-99
  scale_x_continuous(limits = c(0, 99), expand = c(0, 0)) +
  # 自定义y轴,只显示分组标识,隐藏多余刻度
  scale_y_continuous(breaks = c(-3, 3), labels = c("control", "disease"), expand = c(0.1, 0)) +
  # 中间的实线作为时间轴,替代原虚线
  geom_hline(yintercept = 0, color = "black", size = 1) +
  # 美化主题,去掉冗余元素
  theme_minimal() +
  theme(
    axis.title.y = element_blank(),
    panel.grid.y = element_blank(),
    panel.grid.minor.x = element_blank()
  ) +
  labs(x = "Age (Time Axis)", color = "Group", shape = "Gender")

核心调整点

  • 利用stack_pos实现同年龄同组样本的堆叠,避免点重叠;通过正负y值将两组分离在时间轴上下。
  • 用geom_hline在y=0处绘制实线作为中间时间轴,替代原有的虚线。
  • 调整标签位置和轴样式,让图表更符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:57:34