即使没有该间隙的记录,也要断开图形线

Make a graph line break even if there are no records for that gap

我在用 R 中的 plotly 绘制时间序列时遇到问题。 基本上我的数据在一个结构如下的数据框中:

datetime            | measure
2018-04-09 00:40:05 | 3.4
2018-04-09 00:41:00 | 3.9
2018-04-09 00:42:07 | 3.8
2018-04-09 00:43:00 | 3.7
2018-04-09 00:44:00 | 4.2
2018-04-09 00:45:00 | 5.8
2018-04-09 01:15:00 | 5.8

观察间隔不均匀,我每分钟观察一次,但粗略地说,可能会有几秒的差异。 然后我在观察之间有更大的差距,在我放在这里的例子中,最后一次观察和前一次观察之间有 30 分钟的差距。

Plotly 显然是在折线图中连接最后两个观察结果,我想要的实际上是它们之间的空白。

您可以通过将数据分成 "chunks" 并将每个数据绘制为单独的轨迹来实现。可重现的例子:

df <- data.frame(
  time = Sys.time() - c(1:10, 51:60),
  value = runif(20),
  chunk = rep(c("A", "B"), each = 10)
)

p <- plot_ly(data = df[which(df$chunk == "A"),], x = ~time, y = ~value, name = "chunk A", type = "scatter", mode = "lines") %>%
  add_trace(data = df[which(df$chunk == "B"),], x = ~time, y = ~value, name = "chunk B", type = "scatter", mode = "lines")

# or if there are more 'chunks'
p2 <- plot_ly(data = df, x = ~time, y = ~value, color = ~chunk, type = "scatter", mode = "lines")

自然地,您需要找到一种有意义的方法来对数据进行分组,即如果观察之间的时间差大于 [指定您的截止点],则移至新块。

尝试使用 connectgaps=False;检查 https://plotly.com/r/line-charts/#connect-data-gaps