r语言 - 即使该间隙没有记录,也进行图形换行



我在 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显然在折线图中连接了最后两个观察结果,我想要的实际上是它们之间的空白。

您可以通过将数据划分为"块"并将每个块绘制为单独的跟踪来实现此目的。可重现的示例:

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

相关内容

最新更新