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

bil*_*231 15 r ggplot2

我有一个包含多天数据的时间序列.在每一天之间有一个没有数据点的时期.在绘制时间序列时,如何省略这些时间段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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Sve*_*ein 19

首先,创建一个分组变量.如果时差大于1分钟,则两组不同:

Group <- c(0, cumsum(diff(Time) > 1))
Run Code Online (Sandbox Code Playgroud)

现在可以使用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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


csg*_*pie 9

问题是ggplot2如何知道你缺少值?我看到两个选择:

  1. NA值填充你的时间序列
  2. 添加表示"组"的其他变量.例如,

    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))
    
    Run Code Online (Sandbox Code Playgroud)

    在此输入图像描述

  • 你没有把它放在你的问题中;)但你接受的答案只有几个街区更好,这就是我想要的那个. (3认同)