简体   繁体   English

使用dygraph for R仅按年份绘制xts时间序列?

[英]Use dygraph for R to plot xts time series by year only?

I am trying to use the new dygraphs for R library to plot winning times for men and women in the Boston Marathon each year. 我正在尝试使用新的dygraphs为R库绘制每年在波士顿马拉松赛中男性和女性的获胜时间。 I've got a data frame of winning times by second, here's a portion of it: 我有一个获胜时间数据帧,这是其中的一部分:

winners <- data.frame(year=1966:1971, mensec=c(8231, 8145, 8537, 8029, 7830, 8325), womensec=c(12100, 12437, 12600, 12166, 11107, 11310))

But I don't know how to create an xts object from this. 但我不知道如何从中创建一个xts对象。 I can create a regular time series from each column and graph each one using dygraph in a separate graph 我可以从每个列创建一个常规时间序列,并使用dygraph在单独的图表中绘制每个列

men <- ts(winners$mensec, frequency = 1, start=winners$year[1])
dygraph(men)
women <- ts(winners$womensec, frequency = 1, start=winners$year[1])
dygraph(women)

If I try to cbind the time series it won't work in dygraph 如果我尝试cbind时间序列,它将无法在dygraph中工作

both <- cbind(men, women)
dygraph(both)

The error message is 错误消息是

Error in xts(x.mat, order.by = order.by, frequency = frequency(x), ...) : NROW(x) must match length(order.by) xts中的错误(x.mat,order.by = order.by,frequency = frequency(x),...):NROW(x)必须匹配长度(order.by)

Any suggestions? 有什么建议? Thanks 谢谢

This looks like a bug in as.xts.ts . 这看起来像as.xts.ts一个错误。 It uses length(x) to create the sequence of dates for the index, which returns the number of elements for a matrix (not the number of rows). 它使用length(x)来创建索引的日期序列,该序列返回矩阵的元素数(不是行数)。

You can work around it by using as.xts on your ts objects before calling cbind on them. 你可以在ts对象上使用as.xts来解决它,然后再调用cbind上的cbind

both <- cbind(men=as.xts(men), women=as.xts(women))

Looks like Joshua answered the question. 看起来约书亚回答了这个问题。 Here is the full answer with slightly different code and also with a year x-axis formatter. 以下是完整的答案,代码略有不同,也有一年的x轴格式化程序。

library(xts)
library(dygraphs)

winners <- data.frame(
  year=1966:1971
  , mensec=c(8231, 8145, 8537, 8029, 7830, 8325)
  , womensec=c(12100, 12437, 12600, 12166, 11107, 11310)
)

winners_xts <- as.xts(
  winners[-1]
  , order.by = as.Date(
    paste0(winners$year,"-01-01",format="%Y-01-01")
  )
)

dygraph( winners_xts ) %>%
  dyAxis( 
    name="x"
    ,axisLabelFormatter = "function(d){ return d.getFullYear() }"
  )

# using the original data here is a way to merge
#   merge will work just like cbind
#   but need to convert to xts first
men <- ts(winners$mensec, frequency = 1, start=winners$year[1])
women <- ts(winners$womensec, frequency = 1, start=winners$year[1])
do.call(merge,Map(as.xts,list(men=men,women=women)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM