使用 ggplot2 图的不规则时间序列未正确缩放并且看起来很拥挤

irregular time series using ggplot2 plot is not correctly scaled and looks crammed

我想使用 ggplot2 绘制一些股票每小时数据;我会在上面做 TSA,然后想在原始图上添加图层。

我的数据示例如下所示:

                   Date Volume
1   2018-03-01 10:30:00 143432
2   2018-03-01 11:30:00  93522
3   2018-03-01 12:30:00 152178
4   2018-03-01 13:30:00 117424
5   2018-03-01 14:30:00 268167
6   2018-03-01 15:30:00 245504
7   2018-03-01 15:59:00 288977
8   2018-03-02 10:30:00 230484
9   2018-03-02 11:30:00 265244
10  2018-03-02 12:30:00 183313
11  2018-03-02 13:30:00 130850
12  2018-03-02 14:30:00 139846
13  2018-03-02 15:30:00 257797
14  2018-03-02 15:59:00 261628
15  2018-03-05 10:30:00 140620
16  2018-03-05 11:30:00 171228
17  2018-03-05 12:30:00 118685
18  2018-03-05 13:30:00 107209
19  2018-03-05 14:30:00 116918
20  2018-03-05 15:30:00 225035

我创建了一个 zoo 对象(我知道我们也可以使用 xtsirts):

temp <- read.csv('somefile.csv')
zt <- zoo(x = temp, order.by = as.POSIXct(temp$Date))

然后我尝试通过以下方式创建一个 ggplot 对象:

a <- ggplot(data = zt, aes(x = index(zt), y = coredata(zt)))
a + geom_line()

情节如下所示:

显然它没有正确缩放并且情节非常拥​​挤。

如何使用 ggplot2 正确绘制它?

我从一些帮助中知道我可以使用 quantmod 中的 chart_series 来绘制它,但我不确定该函数是为时间序列分析设计的(可能更多用于财务数据绘制)和因此可能不够灵活,无法添加图层。

编辑

通常我希望我的情节看起来像这样:

library(xts)
library(quantmod)
xxt <- xts(x = temp$Volume, order.by = as.POSIXct(temp$Date))
chart_series(xxt)

我不需要所有的美学,只要它的绘制方式就是我想要的。感觉 quantmod 图表消除了所有差距。

我试了 45 分钟让 ggplot 玩得很好,结果空无一人。我将与 'zoo' 团队讨论添加一个选项 autoplot.zoo() 这样你就可以调用 autoplot(zt, new.option = TRUE) 来生成你想要的情节。


您说得对,quantmod::chart_Series() 主要用于金融时间序列。 zoo和xts好像很熟悉,都是支持任意时间序列的数据类

您可以使用 plot.xts()。请务必设置 observation.based = TRUE,以便 x 轴在观察之间具有相等的 space 数量,而不管它们之间的时间长短。

# reproducible data
x <- structure(c(143432L, 93522L, 152178L, 117424L, 268167L, 245504L, 288977L,
230484L, 265244L, 183313L, 130850L, 139846L, 257797L, 261628L, 140620L, 171228L,
118685L, 107209L, 116918L, 225035L), .Dim = c(20L, 1L),
index = structure(c(1519921800, 1519925400, 1519929000, 1519932600, 1519936200,
1519939800, 1519941540, 1520008200, 1520011800, 1520015400, 1520019000,
1520022600, 1520026200, 1520027940, 1520267400, 1520271000, 1520274600,
1520278200, 1520281800, 1520285400), tzone = "", tclass = c("POSIXct", "POSIXt")),
class = c("xts", "zoo"), .indexCLASS = c("POSIXct", "POSIXt"),
tclass = c("POSIXct", "POSIXt"), .indexTZ = "", tzone = "")

现在对 xts 对象调用 plot()

plot(x, observation.based = TRUE, major.ticks = "hours")