英文:
Phase diagram with vertical lines connecting discrete phases or states
问题
我使用 ggplot2
在 R 中绘制了一个状态图。离散的垂直轴显示了几个状态,水平轴显示时间。线条连接了一个阶段的起点和终点,不同的颜色表示不同的状态。这是一个示例:
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)
如何连接一个阶段的终点与下一个阶段(不同状态)的起点,使用黑色垂直线?每个时间点都有且仅有一个状态,即没有重叠的状态和空时间点。
英文:
I draw a state diagram using ggplot2
in R. The discrete vertical axis shows several states, and the horizontal axis shows time. Lines connect the start and end points of a phase, with different colours per state. Here is an example:
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)
How can I connect the end point of a phase with the start point of the next phase (in a different state) using a black, vertical line? Each time point has exactly one state, i.e., there are no overlapping states and no empty time points.
答案1
得分: 0
以下是翻译好的部分:
一种选择是将您的数据重塑为长格式,并使用 group
函数来绘制段以及通过 geom_line
函数绘制连接线:
library(ggplot2)
library(dplyr, warn=FALSE)
library(tidyr)
states1 <- states %>%
mutate(id = row_number()) %>%
pivot_longer(c(start, end))
ggplot(states1, aes(
x = value,
y = state,
color = state,
)) +
geom_line(aes(group = value),
color = "black",
linewidth = 3, lineend = "round"
) +
geom_line(aes(group = id), linewidth = 3, lineend = "round")
英文:
One option would be to reshape your data to long and use the group
aes to draw the segments as well as the connecting lines via geom_line
:
library(ggplot2)
library(dplyr, warn=FALSE)
library(tidyr)
states1 <- states |>
mutate(id = row_number()) |>
pivot_longer(c(start, end))
ggplot(states1, aes(
x = value,
y = state,
color = state,
)) +
geom_line(aes(group = value),
color = "black",
linewidth = 3, lineend = "round"
) +
geom_line(aes(group = id), linewidth = 3, lineend = "round")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论