rcharts: nPlot Formating x-axis with dates

断了今生、忘了曾经 提交于 2019-12-24 14:40:17

问题


I have a data.frame with dates and integers:

  df <- data.frame(date=seq.Date(from=as.Date("2012/01/01"), to=as.Date("2012/02/28"), by="1 day"), y=1:59)

I want to plot the data.frame with rCharts nPlot:

  n <- nPlot(y ~ date, group = "team", data = df, type = "lineChart")
  n$xAxis(
    tickFormat =   "#!
      function(d) {return d3.time.format('%Y-%M-%d')(new Date(d));}
    !#",
    rotateLabels = -90
  )
  n

But the x-axis isn't formatted correctly.

So how do I format the dates correctly?


回答1:


In R as.numeric(someDate) is days since origin. Here we need milliseconds from origin. So it should be

  df <- data.frame(date=seq.Date(from=as.Date("2012/01/01", origin="1970-01-01"), to=as.Date("2012/02/28", origin="1970-01-01"), by="1 day"), y=1:59)

  n <- nPlot(y ~ date, group = "team", data = df, type = "lineChart")
  n$xAxis(
    tickFormat =   "#!
      function(d) {return d3.time.format('%Y-%m-%d')(new Date(d*1000*3600*24));}
    !#",
    rotateLabels = -90
  )
  n



回答2:


%M is minute, what you want is %m which will get you months:

 n <- nPlot(y ~ date, group = "team", data = df, type = "lineChart")
  n$xAxis(
    tickFormat =   "#!
      function(d) {return d3.time.format('%Y-%m-%d')(new Date(d));}
    !#",
    rotateLabels = -90
  )
  n


来源:https://stackoverflow.com/questions/24344794/rcharts-nplot-formating-x-axis-with-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!