如何绘制不规则的时间序列,使x轴点等距?

时间:2016-01-21 00:55:27

标签: r plot time-series

我有一个不规则的时间序列。每行代表聚合显示HLOC的x个刻度,(日期时间,价格,体积),使用每个组的第一个刻度来设置行的DateTime。

"Time","Open","High","Low","Close","SumVol","SumTicks"
...
2016-01-15 11:14:43,4.74,4.74,4.7325,4.735,298,250
2016-01-15 11:14:56,4.735,4.735,4.7275,4.7325,475,250
2016-01-15 11:16:49,4.7325,4.76,4.7275,4.7575,903,250
2016-01-18 17:00:15,4.7575,4.765,4.75,4.755,327,250
2016-01-18 17:02:17,4.755,4.7575,4.7375,4.7375,398,250
2016-01-18 17:05:23,4.7375,4.7375,4.715,4.7175,395,250
2016-01-18 17:08:56,4.7175,4.72,4.7125,4.7175,509,250
2016-01-18 17:22:06,4.7175,4.725,4.7175,4.7175,326,250
2016-01-18 17:57:25,4.7175,4.7225,4.7125,4.7125,349,250
2016-01-18 18:33:55,4.7125,4.725,4.7125,4.725,293,250
2016-01-18 20:54:43,4.725,4.735,4.725,4.7275,272,250
2016-01-18 22:49:55,4.7275,4.73,4.72,4.7225,335,250
2016-01-19 00:14:32,4.7225,4.73,4.7225,4.73,430,250
...

因为这些数据会在周末进行,并且包括活动较少的夜间交易,所以记录的时间间隔非常不均匀。我想在图表中包含日期/时间信息以供一般参考,但保持均匀分布的条形,如下面第二个图所示。

而不是:

enter image description here

我希望它看起来像这样,但是使用日期/时间而不是行号:

enter image description here

是否有某种方法可以将第二个图表中的x轴与日期/时间列(或者例如每10个条目)垂直叠加?

我尝试了将时间转换为因子的建议,但结果图不会连接点     plot(Close~as.factor(Time),data = dtTicksSum,type =“s”) enter image description here

2 个答案:

答案 0 :(得分:1)

正如评论中的tospig所指出的,这有效(经过测试验证):

plot(Close ~ as.factor(Time), data = dtTicksSum)

as.factor将以匹配的时间顺序创建整数代码。

答案 1 :(得分:1)

只需扩展@SenorO的答案,并使用您提供的数据

dtTicksSum <- data.frame(dateTime = readLines(textConnection("2016-01-15 11:14:43,4.74,4.74,4.7325,4.735,298,250
2016-01-15 11:14:56,4.735,4.735,4.7275,4.7325,475,250
2016-01-15 11:16:49,4.7325,4.76,4.7275,4.7575,903,250
2016-01-18 17:00:15,4.7575,4.765,4.75,4.755,327,250
2016-01-18 17:02:17,4.755,4.7575,4.7375,4.7375,398,250
2016-01-18 17:05:23,4.7375,4.7375,4.715,4.7175,395,250
2016-01-18 17:08:56,4.7175,4.72,4.7125,4.7175,509,250
2016-01-18 17:22:06,4.7175,4.725,4.7175,4.7175,326,250
2016-01-18 17:57:25,4.7175,4.7225,4.7125,4.7125,349,250
2016-01-18 18:33:55,4.7125,4.725,4.7125,4.725,293,250
2016-01-18 20:54:43,4.725,4.735,4.725,4.7275,272,250
2016-01-18 22:49:55,4.7275,4.73,4.72,4.7225,335,250
2016-01-19 00:14:32,4.7225,4.73,4.7225,4.73,430,250")))

library(tidyr)

dtTicksSum <- dtTicksSum %>%
    separate(dateTime, into=c("Time","Open","High","Low","Close","SumVol","SumTicks"), sep=",")

dtTicksSum$Time <- as.POSIXct(dtTicksSum$Time)
plot(Close ~ Time, data = dtTicksSum, type ="s") 

enter image description here

## using a factor 
dtTicksSum$fac_time <- as.factor(dtTicksSum$Time)
plot(Close ~ fac_time, data = dtTicksSum, type ="s") 

enter image description here

并使用ggplot2

library(ggplot2)
ggplot(data=dtTicksSum, aes(x=fac_time, y=Close, group=1)) +
    geom_line() +
    theme_bw()

enter image description here

参考:using groups in ggplot::geom_line()