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

如何在R语言中绘制带时间标注的事件时序图?

R语言实现事件时间轴绘图(Y轴为事件名称,X轴标注时间)

数据准备与整理

首先需要将原始的宽格式数据(同一事件多次时间用分号分隔)转换为长格式(每个事件-时间对单独一行),方便后续绘图。

输入原始数据

直接将你提供的数据构造为数据框:

# 原始数据
raw_data <- data.frame(
  event = c("event1", "event2", "event3", "event4", "event5", "event6", "event7", 
            "event8", "event9", "event10", "event11", "event12", "event13", 
            "event14", "event15", "event16", "event17"),
  times = c("14:30:00;16:30:00;17:15:00;18:30:00;19:30:00",
            "14:30:00",
            "13:45:00;15:15:00;17:15:00",
            "13:15:00;14:15:00;15:30:00;16:25:00;17:55:00;19:40:00",
            "21:00:00",
            "13:10:00;14:15:00;15:55:00;17:40:00",
            "16:45:00;18:15:00;20:30:00",
            "14:00:00;16:45:00;18:30:00",
            "15:00:00;17:45:00;20:00:00",
            "21:00:00",
            "13:00:00",
            "14:00:00;14:30:00;15:00:00;15:30:00;16:00:00;16:30:00;17:00:00;17:30:00;18:00:00;18:30:00;19:00:00;19:30:00;20:00:00",
            "14:00:00;14:25:00;15:10:00;15:25:00",
            "17:50:00;18:15:00;19:15:00;20:25:00;20:45:00",
            "14:15:00;16:00:00;17:15:00;18:45:00;19:45:00",
            "14:30:00;16:00:00;17:30:00",
            "19:15:00")
)

转换为长格式并处理时间

使用tidyr::separate_rows拆分分号分隔的时间,再将时间转换为可识别的时分秒类型:

library(tidyverse)
library(hms) # 专门处理时分秒的轻量包

clean_data <- raw_data %>%
  separate_rows(times, sep = ";") %>%
  mutate(
    time_hms = as_hms(times), # 转换为时分秒格式,便于坐标轴处理
    # 强制保持事件的原始顺序,避免ggplot自动按字母排序
    event = factor(event, levels = raw_data$event)
  )

绘制时间轴图

使用ggplot2实现需求:Y轴为事件名称(每行对应一个事件),X轴为时间(垂直显示标签),并标注每个时间点的具体时间:

ggplot(clean_data, aes(x = time_hms, y = event)) +
  # 绘制事件时间点
  geom_point(color = "#2c3e50", size = 3) +
  # 标注时间文本,向右偏移避免遮挡点
  geom_text(aes(label = times), hjust = -0.1, color = "#e74c3c", size = 3.5) +
  # 设置坐标轴标题
  labs(x = "时间", y = "事件名称") +
  # 将X轴时间标签垂直显示
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) +
  # 使用极简主题提升可读性
  theme_minimal() +
  # 扩展X轴范围,避免边缘时间文本被截断
  scale_x_time(limits = c(as_hms("12:30:00"), as_hms("21:30:00")))

关键细节说明

  • separate_rows:核心函数,一键拆分同一事件的多个时间为单独行。
  • factor(event, levels = raw_data$event):确保事件顺序和原始数据一致,不会被自动排序打乱。
  • as_hms:比通用的POSIXct更适合仅含时分秒的数据,避免日期干扰。
  • geom_text的hjust = -0.1:调整文本位置,若仍有拥挤可缩小size参数或增加X轴范围。
  • 若需要反转Y轴事件顺序(从下到上显示event1到event17),可添加scale_y_discrete(limits = rev(raw_data$event))。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:51:29