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

如何用R的ggplot2为状态图添加跨状态黑色垂直连接线

用ggplot2绘制状态图时添加状态切换的垂直连接线

你已经通过以下代码实现了纵轴为离散状态、横轴为时间的状态图,不同状态阶段用对应颜色的线段展示:

library("ggplot2")

states <- data.frame(state = factor(c(2, 1, 2, 1)),
                     start = c(0.5, 1.5, 3.5, 5.5),
                     end = c(1.5, 3.5, 5.5, 7.5))

ggplot(states, aes(x = start,
                   xend = end,
                   y = state,
                   yend = state,
                   color = state)) + 
  geom_segment(size = 3)

要在相邻不同状态的阶段之间添加黑色垂直连接线,只需按以下步骤操作:

  • 构造连接线数据:提取相邻状态的切换时间点、前后状态,生成用于绘制垂直线的数据集。因为无时间空白,前一阶段的end与后一阶段的start是同一时间点。
  • 添加垂直连线图层:在原有绘图代码基础上,新增geom_segment图层,专门绘制黑色垂直线,避免继承全局的颜色映射。

完整代码如下:

library("ggplot2")

states <- data.frame(state = factor(c(2, 1, 2, 1)),
                     start = c(0.5, 1.5, 3.5, 5.5),
                     end = c(1.5, 3.5, 5.5, 7.5))

# 构造连接线数据:取前一行的end时间、状态,和当前行的状态
connect_lines <- data.frame(
  x = head(states$end, -1),
  xend = head(states$end, -1),
  y = head(states$state, -1),
  yend = tail(states$state, -1)
)

ggplot() +
  # 先画状态阶段的彩色线段
  geom_segment(data = states, 
               aes(x = start, xend = end, y = state, yend = state, color = state),
               size = 3) +
  # 再画状态切换的黑色垂直线
  geom_segment(data = connect_lines,
               aes(x = x, xend = xend, y = y, yend = yend),
               color = "black", size = 1)

这段代码会在每个状态切换的时间点,用黑色垂直线连接前后两个状态的线段,完成状态图的补全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:17:37