2017-08-02 52 views
-1

我有一个数据框,其结构如下(空间明智的两个事件的到达和离开时间,U1和U2)。我想绘制一个时间 - 空间图,以便x轴显示时间刻度,y轴显示空间。我曾尝试过几件事情,比如剧情功能,但是,无法管理它。任何人都可以帮助我呢?谢谢!在时间空间图中绘制多列

Space U2  U1 
    A  16:14:00 16:29:00 
    A  18:56:00 19:05:00 
    B  19:14:00 19:16:59 
    B  19:32:00 19:39:59 
    C  19:50:00 19:57:59 
    C  20:10:59 20:15:00 
    D  16:21:00 16:39:00 
    D  16:32:00 16:54:00 
    E  16:48:59 17:10:00 
    E  17:01:59 17:24:00 

更新:我已经能够绘制与ggplot的东西,但是,空间之间的跳跃点未连接。任何想法如何连接它们?

df%>% mutate(Space= factor(Space, levels=unique(Space))) %>% gather(var,  val, -Space)%>% ggplot(aes(Space, val, color = var,group = interaction(val,Space,var)))+ geom_line() 

回答

1

我的任择议定书的要求的理解如下:

  1. 每个空间的第一行给出了到达时间和第二排的发车时间。因此,事件到达时间A的到达时间为16:29,出发时间为19:05。

  2. 在图表中,每个事件和空间的到达和离开时间应由线段连接,沿着x轴的时间和沿y轴的空间。

要绘制使用geom_segment()数据需要被再成形,使得到达和离开时间一行内出现在两列,而不是两行一个低于其它的线段。

library(data.table) #CRAN version 1.10.4 used 

# use chaining, start with converting a copy of df to class data.table 
pd <- data.table(df)[ 
    # reshape from wide to long form to get all events in one column, 
    # thereby renaming conveniently 
    , melt(.SD, id.var = "Space", variable.name = "Event", variable.factor = FALSE)][ 
    # reshape from long to wide to get arrival and departure times 
    # for each space and each event in one row 
    # use factor to give meaningful names to columns (instead of numbers) 
    , dcast(.SD, Space + Event ~ factor(rowid(Space, Event), 
             labels = c("Arrival", "Departure")))] 

pd 
Space Event Arrival Departure 
1:  A U1 16:29:00 19:05:00 
2:  A U2 16:14:00 18:56:00 
3:  B U1 19:16:59 19:39:59 
4:  B U2 19:14:00 19:32:00 
5:  C U1 19:57:59 20:15:00 
6:  C U2 19:50:00 20:10:59 
7:  D U1 16:39:00 16:54:00 
8:  D U2 16:21:00 16:32:00 
9:  E U1 17:10:00 17:24:00 
10:  E U2 16:48:59 17:01:59 

现在,在重构数据可绘制:这是通过使用melt()dcast()data.table包装来实现

library(ggplot2) 
ggplot(pd) + 
    aes(x = Arrival, xend = Departure, y = Space, yend = Space, colour = Event) + 
    geom_segment() + 
    geom_point() + geom_point(aes(x = Departure)) + 
    xlab("Time") + 
    theme_bw() 

enter image description here

注意一些线段确实重叠但是指出了开始和结束点。

避免出现重叠绘图的其他选项可能是在y轴上刻画或绘制交互变量interaction(Space, Event)(或interaction(Event, Space),以获得不同的顺序)。