相图,用垂直线连接离散的相或状态。

huangapple go评论54阅读模式
英文:

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(&quot;ggplot2&quot;)

states &lt;- 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 &lt;- states |&gt; 
  mutate(id = row_number()) |&gt; 
  pivot_longer(c(start, end))
  
ggplot(states1, aes(
  x = value,
  y = state,
  color = state,
)) +
  geom_line(aes(group = value),
    color = &quot;black&quot;,
    linewidth = 3, lineend = &quot;round&quot;
  ) +
  geom_line(aes(group = id), linewidth = 3, lineend = &quot;round&quot;)

相图,用垂直线连接离散的相或状态。

huangapple
  • 本文由 发表于 2023年7月14日 08:03:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定