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

如何用ggplot2绘制按个体分组的二元变量时间轴交叉点

解决方案

要实现每个个体对应时间序列线、事件发生处用交叉/点标记的需求,可按以下方式修改绘图代码:

方案一:基线+事件标记(更突出事件位置)

这种方式用水平基线展示时间跨度,仅在事件发生处标记,视觉更简洁:

library(ggplot2)
library(dplyr)

# 生成数据集
access <- rbinom(n=500,size=1,prob=0.40)
id <- rep(1:10, each = 50)   
day_id <- rep(1:50, 10)
da <- data.frame(access = access, id = id, day_id = day_id)

# 绘图代码
da %>%
  ggplot(aes(x = day_id)) +
  # 绘制贯穿50天的水平基线
  geom_hline(aes(yintercept = 0), color = "gray50") +
  # 在access=1的位置用红色交叉标记事件
  geom_point(data = . %>% filter(access == 1), aes(y = 0), shape = 4, size = 2, color = "red") +
  # 按个体分面
  facet_wrap(~id) +
  # 调整坐标轴与主题
  labs(x = "天数", y = "") +
  theme_minimal() +
  theme(axis.text.y = element_blank(), axis.ticks.y = element_blank())

方案二:完整二元序列线+事件标记

如果需要保留0/1的完整时间序列变化,同时突出事件:

da %>%
  ggplot(aes(x = day_id, y = access)) +
  # 绘制每个个体的0/1变化折线
  geom_line(color = "gray50") +
  # 在事件发生处用红色交叉标记
  geom_point(data = . %>% filter(access == 1), shape = 4, size = 2, color = "red") +
  facet_wrap(~id) +
  labs(x = "天数", y = "是否发生事件") +
  theme_minimal()

关键调整说明

  • 用filter(access == 1)精准筛选事件记录,避免无关点干扰
  • shape=4对应交叉标记,若要实心点可改为shape=16
  • 分面facet_wrap(~id)保证每个个体单独展示时间序列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 11:27:14