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

在R中基于相对时间点绘制处理前后Var1变化图

用ggplot绘制处理前后Var1的变化图(以处理时间为X轴0点)

步骤1:数据预处理

首先要给每个个体(ID)计算相对于处理时间的月份:把首次出现BeforeAfter=TRUE的月份设为0,处理前的月份为负数,处理后的为正数。用dplyr包完成分组计算:

# 加载所需包
library(dplyr)
library(ggplot2)

# 处理数据:计算每个ID的处理月份,再得到相对月份
processed_data <- larger_sample %>%
  group_by(ID) %>%
  # 定位每个ID首次出现TRUE的月份
  mutate(treatment_month = Month[min(which(BeforeAfter == TRUE))]) %>%
  # 计算相对月份:当前月份减去处理月份
  mutate(relative_month = Month - treatment_month) %>%
  ungroup()

步骤2:绘制ggplot图表

用处理好的数据绘图,实现目标效果:展示个体趋势+整体均值趋势,突出X轴0点(处理时间):

ggplot(processed_data, aes(x = relative_month, y = Var1)) +
  # 绘制每个个体的趋势线,浅灰色半透明避免杂乱
  geom_line(aes(group = ID), color = "#cccccc", alpha = 0.6) +
  # 绘制整体均值的趋势线,加粗突出
  stat_summary(fun = mean, geom = "line", color = "#2c3e50", size = 1.2) +
  # 绘制均值的置信区间,展示数据波动(可选)
  stat_summary(fun.data = mean_se, geom = "ribbon", fill = "#3498db", alpha = 0.2) +
  # 用虚线突出处理时间点(X=0)
  geom_vline(xintercept = 0, color = "#e74c3c", linetype = "dashed", size = 1) +
  # 设置坐标轴标签和标题
  labs(
    x = "相对于处理时间的月份",
    y = "Var1数值",
    title = "处理前后Var1的变化趋势",
    subtitle = "0点为首次处理时间"
  ) +
  # 调整主题优化视觉效果
  theme_minimal() +
  theme(
    plot.title = element_text(hjust = 0.5, size = 14, face = "bold"),
    plot.subtitle = element_text(hjust = 0.5, size = 12),
    axis.title = element_text(size = 11)
  )

关键说明

  • 数据预处理:通过分组定位每个ID的首次处理月份,再计算相对月份,这是实现X轴以0为处理基准点的核心。
  • 绘图逻辑:
    • 个体趋势线用浅灰半透明,避免掩盖整体趋势;
    • 均值趋势线+置信区间,清晰展示群体层面的变化规律;
    • 红色虚线明确标记处理时间节点,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:02:01