如何使用ggplot2绘制2D时间序列

时间:2016-06-10 13:53:56

标签: r ggplot2 time-series

我的数据如下:

d <- data.frame(x=rnorm(40),
                y=rnorm(40), 
                t=rep(sample(1:10, replace = F), times=4), 
                v=rep(1:4, each=10))

ggplot(d, aes(x=x, y=y)) +
  geom_point() +
  facet_wrap(~v)

TimeSeries

我想添加连接由时间变量(t)排序的点的线(理想情况下带箭头指示方向)。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

事实证明使用geom_path

非常容易
library(dplyr)
library(ggplot2)

d <- data.frame(x=rnorm(40),
                y=rnorm(40), 
                t=rep(sample(1:10, replace = F), times=4), 
                v=rep(1:4, each=10))

d <- arrange(d, t)
ggplot(d, aes(x=x, y=y)) +
  geom_point() +
  geom_path(arrow=arrow()) +
  facet_wrap(~v)

enter image description here

答案 1 :(得分:2)

正如您在上一个答案中所看到的那样,最后的箭头有时令人困惑,这里有一个在每个点之间添加箭头的提示。

2个解决方案:

  1. 箭头到达下一个点
  2. enter image description here

    d <- data.frame(x=rnorm(40),
                y=rnorm(40), 
                t=rep(sample(1:10, replace = F), times=4), 
                v=rep(1:4, each=10))
    
    d = d[order(d$t),]
    d = d[order(d$v),]
    
    d$y_arrow = c(tail(d$y, n=-1), NA)
    d$x_arrow = c(tail(d$x, n=-1), NA)
    d$y_arrow[d$t == 10] <- NA
    d$x_arrow[d$t == 10] <- NA
    
    ggplot(d, aes(x=x, y=y, group = v)) + geom_point() + facet_wrap(~v) + 
    geom_path()+ geom_segment(aes(xend=x_arrow, yend=y_arrow), 
    arrow=arrow(length=unit(0.3,"cm"))) + theme_bw()
    
    1. 箭头是中途
    2. enter image description here

      d <- data.frame(x=rnorm(40),
                  y=rnorm(40), 
                  t=rep(sample(1:10, replace = F), times=4), 
                  v=rep(1:4, each=10))
      
      d = d[order(d$t),]
      d = d[order(d$v),]
      
      d$y_arrow = c((tail(d$y, n=-1) + head(d$y, n=-1))/2, NA)
      d$x_arrow = c((tail(d$x, n=-1) + head(d$x, n=-1))/2, NA)
      d$y_arrow[d$t == 10] <- NA
      d$x_arrow[d$t == 10] <- NA
      
      
      ggplot(d, aes(x=x, y=y, group = v)) + geom_point() + facet_wrap(~v) + 
      geom_path()+ geom_segment(aes(xend=x_arrow, yend=y_arrow), 
      arrow=arrow(length=unit(0.3,"cm"))) + theme_bw()