使用 plot.ts() 的时间序列的日期转换问题 [英] Date conversion issue for time series using plot.ts()

查看:61
本文介绍了使用 plot.ts() 的时间序列的日期转换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 yyyy-mm-dd 格式的日期和股价的数据框,但是在使用 plot.ts() 绘制它时我看不到 x 轴中的日期.我已经尝试了下面提到的一些替代方法,但它们都不起作用.

I have a dataframe with date in yyyy-mm-dd format and share prices but I can't see the date in the x axis when plotting it using plot.ts(). I have tried a few alternatives mentioned below but they did not work.

我使用

  1. data$Date<-as.Date(data$Date, "%Y-%m-%d")
  2. data$Date<-ymd(data$Date) 使用 lubridate 包
  1. data$Date<-as.Date(data$Date, "%Y-%m-%d") OR
  2. data$Date<-ymd(data$Date) using the lubridate package

然后做了

bby <- ts(data=data$Share_price, frequency=2, start=c(data[1,"Date"]))
plot.ts(bby))

失败了.

我也试过

bby <- ts(data=data$Share_price, frequency=2,
     start=as.Date("2017-10-05"), end=as.Date("2019-10-04"))`

然后plot.ts(bby)

但它再次不起作用.我总是得到下图:

but again it did not work. I always end up with the below graph:

感谢您的帮助.

推荐答案

ts 设置有点笨拙,它的情节并不总是最友好的.您可以按如下方式设置数据.请注意,您需要以相当痛苦的方式为下面的时间序列对象指定开始",然后(因为它只接受固定的时间间隔)您将失去原始系列中的日间差距:

The ts setup is a bit clunky and its plots are not always the friendliest. You could set up your data as follows. Note that you need to specify the 'start' for the time series object below in a rather painful manner, and then (because it only accepts regular time intervals) you lose the day gap in the original series:

z <- seq.Date(as.Date('2017-10-05'), by = 1, length.out = 8)
data <- data.frame(Date = z[-(3:4)],
                   Share_price = c(1708.84, 1718.40, 1724.14, 1762.39, 1766.21, 1813.07))
myts <- ts(data$Share_price,
           start = c(2017, as.numeric(format(data$Date[1], "%j"))),
           frequency = 365)
plot(myts)

x 轴现在具有自 2017 年以来的小数点偏移量.

The x-axis now has decimal offsets from the year 2017.

也许这里的 xts 包更好?它可以处理不规则的时间索引.

Perhaps the xts package is better here? It can handle irregular time indices.

library(xts)
myxts <- xts(data$Share_price, data$Date)
plot(myxts)

请参阅 plot.xts() 文档,了解用于美化图表的各种花里胡哨的内容.

See the plot.xts() documentation for all sorts of bells and whistles to embellish your graph.

这篇关于使用 plot.ts() 的时间序列的日期转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆