【问题标题】:rcharts: nPlot Formating x-axis with datesrcharts:nPlot 用日期格式化 x 轴
【发布时间】:2014-08-12 05:54:17
【问题描述】:

我有一个带有日期和整数的 data.frame:

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

我想用 rCharts nPlot 绘制 data.frame:

  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

但是 x 轴的格式不正确。

那么如何正确格式化日期呢?

【问题讨论】:

    标签: r rcharts


    【解决方案1】:

    在 R 中 as.numeric(someDate) 是自起源以来的天数。在这里,我们需要从原点开始的毫秒数。 所以应该是

      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 是分钟,你想要的是 %m,这会让你几个月:

       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
      

      【讨论】:

      • 啊,我错过了。但这并不能解决问题。年份还是错的!对于所有日期,我仍然得到 1970-01-01。
      • 尝试将大小写更改为%y?
      • 不,然后我得到 70-01-01。所以 df$date 的类型或 tichFormat 中的函数一定有问题...
      • 如stackoverflow.com/questions/19459687/… d 以毫秒为单位,所以应该是function(d) {return d3.time.format('%Y-%m-%d')(new Date(d*1000));} 但输出还是不行。
      猜你喜欢
      • 2014-06-06
      • 2021-12-09
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2020-10-06
      • 2019-10-31
      • 2018-06-28
      相关资源
      最近更新 更多