ggplot2 时间序列绘图:如何在没有数据点的时候省略时间段?

17

我有一系列跨越多天的时间序列数据,在每个相邻的两天之间存在一个没有数据点的时间段。如何在使用ggplot2绘制时间序列图时省略这些时间段?

以下是一个人工示例,我该如何去除两个没有数据的时间段?

代码:

Time = Sys.time()+(seq(1,100)*60+c(rep(1,100)*3600*24, rep(2, 100)*3600*24, rep(3, 100)*3600*24))
Value = rnorm(length(Time))
g <- ggplot() 
g <- g + geom_line (aes(x=Time, y=Value))
g

在此输入图像描述

3个回答

21

首先,创建一个分组变量。在这里,如果时间差大于1分钟,则两个组是不同的:

Group <- c(0, cumsum(diff(Time) > 1))

现在可以使用facet_grid和参数scales = "free_x"创建三个不同的面板:

library(ggplot2)
g <- ggplot(data.frame(Time, Value, Group)) + 
  geom_line (aes(x=Time, y=Value)) +
  facet_grid(~ Group, scales = "free_x")

enter image description here


1
当你只有几个块的时候,这绝对是最好的解决方案。 - csgillespie
谢谢。我试图在一个图中完成这个任务,但是你的方法看起来仍然可行。其他包如quantmod可以完美地完成这个任务,但我想这不是ggplot2应该做的事情。 - billlee1231

9
问题在于ggplot2如何知道您有缺失值?我看到两个选项:
  1. Pad out your time series with NA values
  2. Add an additional variable representing a "group". For example,

    dd = data.frame(Time, Value)
    ##type contains three distinct values
    dd$type = factor(cumsum(c(0, as.numeric(diff(dd$Time) - 1))))
    
    ##Plot, but use the group aesthetic
    ggplot(dd, aes(x=Time, y=Value)) +
          geom_line (aes(group=type))
    

    gives

    enter image description here


谢谢。但我宁愿完全摆脱之间的空白期间(意思是甚至不显示在x轴上)。 - billlee1231
3
你在问题中没有提到那个信息 ;) 但是你接受的答案更简洁好看,只需要写几行代码,我也会选择那个答案。 - csgillespie

3

csgillespie提到了用NA填充,但更简单的方法是在每个块后面添加一个NA:

Value[seq(1,length(Value)-1,by=100)]=NA

这里的 -1 是为了避免警告。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接