nPlot的时间序列图

时间:2014-02-11 14:27:49

标签: r rcharts

我正在尝试使用nPlot绘制时间序列图,并且难以以理想的方式呈现X轴的标签。 我一直在寻找这个问题之前是否已经出现但它没有解决方案(据我设法找到),我想知道是否已有解决方案?

在这种情况下,我得到介于-1和1之间的X轴,并且图上没有线:

date = c("2013-07-22", "2013-07-29" ,"2013-08-05", "2013-08-12", "2013-08-19","2013-08-26", "2013-09-02" ,"2013-09-09" ,"2013-09-16")
test = as.data.frame(date)
test$V1 = c("10","11","13","12","11","10","15","12","9")
test$V2 = c("50","51","53","52","51","50","55","52","59")     
test1 = melt(test,id = c("date"))

n1 = nPlot(value ~ date, group = "variable", data = test1, type="lineWithFocusChart") 

如果我添加而不是再次绘图:

test1$date = as.Date(test1$date)

我得到想要的图表,但X轴标签是数字形式(15900 ..)

感谢。

1 个答案:

答案 0 :(得分:2)

这是让它发挥作用的一种方法。我对您的代码进行了一些更改。一,我已经将V1和V2设为数字,因为你想在y轴上绘制数字。其次,我添加了一个实用程序函数to_jsdate,它接受​​字符日期并将其转换为javascript日期(1970-01-01之后的毫秒数)。在rCharts中,日期处理仍然有点原始,但我们正在努力使其更好。

date = c("2013-07-22", "2013-07-29" ,"2013-08-05", "2013-08-12", "2013-08-19",
  "2013-08-26", "2013-09-02" ,"2013-09-09" ,"2013-09-16")
test = as.data.frame(date)
test$V1 = as.numeric(c("10","11","13","12","11","10","15","12","9"))
test$V2 = as.numeric(c("50","51","53","52","51","50","55","52","59"))     
test1 = reshape2::melt(test,id = c("date"))

to_jsdate <- function(date_){
  val = as.POSIXct(as.Date(date_),origin="1970-01-01")
  as.numeric(val)
}


test1 = transform(test1, date2 = to_jsdate(date))

n1 = nPlot(value ~ date2, group = "variable", data = test1, type="lineWithFocusChart")
n1$xAxis(tickFormat = "#! function(d){ 
  return d3.time.format('%Y-%m-%d')(new Date(d*1000))
} !#") 
n1