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

标签 r ggplot2 time-series xts zoo

我有一些股票每小时数据,我想使用 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()

情节如下:

enter image description here

显然它的比例不正确,而且情节非常拥​​挤。

如何使用 ggplot2 正确绘制它?

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

编辑

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

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

enter image description here

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

最佳答案

我尝试了 45 分钟让 ggplot 正常运行,但一无所获。我将与“zoo”团队讨论添加选项 autoplot.zoo(),以便您只需调用 autoplot(zt, new.option = TRUE) 即可生成你想要的情节。


您是对的,quantmod::chart_Series() 主要用于金融时间序列。看来你对zoo和xts很熟悉,它们是支持任何时间序列的数据类。

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

# 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")

enter image description here

关于r - 使用 ggplot2 绘图的不规则时间序列未正确缩放并且看起来很拥挤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50635444/

相关文章:

r - 改进我的 R 代码以计算数据框的 Z 分数

r - 修改曲线以防止初始参数估计时出现奇异梯度矩阵

r - 有没有办法让 ggplot2 中的position_jitterdodge在使用两个数据集时按两个分类变量进行排序?

python - 我收到错误 "ValueError: endog is required to have ndim 1 but has ndim 2"

sql - 计算列组合的出现次数

r - 将字符串中由两个不同分隔符分隔的值列表转换为单独的行

r - 如何从另一个 df 的值子集创建一个新的 df?

python - 将组分配给 Pandas 列中的连续 1

r - ggplot2:更改图例中的因子顺序

r - 如何躲避重叠的线段以保持它们平行