【问题标题】:Displaying Relative Time on x-axis with d3.js使用 d3.js 在 x 轴上显示相对时间
【发布时间】:2012-08-20 17:28:45
【问题描述】:

我正在尝试使用 nvd3.js 显示一段时间内的评分(近乎实时;数据每 3 分钟更新一次)。现在数据似乎显示正确,除了 x 轴显示的纪元时间不太可读。如何让 x 轴显示“x 分钟前”而不是纪元时间?

这是我正在使用的代码:

nv.addGraph(function() {
  var chart = nv.models.lineChart();

  chart.xAxis
      .axisLabel('Time')
      .tickFormat(d3.format('r'));

  chart.yAxis
      .axisLabel('Rating')
      .tickFormat(d3.format('.2f'));

  d3.select('#chart svg')
      .datum(data())
    .transition().duration(500)
      .call(chart);

  nv.utils.windowResize(chart.update);

  return chart;
});

function data() {
  var data = [ { x: 1345457533, y: -0.0126262626263 },
               { x: 1345457409, y: 0.0224089635854 },
               { x: 1345457288, y: 0.0270935960591 },
               { x: 1345457168, y: -0.0378151260504 },
               { x: 1345457046, y: -0.115789473684 } ]

  return [
    {
      values: data,
      key: "Sample1",
      color: "#232066"
    }
  ];
}

【问题讨论】:

    标签: javascript d3.js nvd3.js


    【解决方案1】:

    为标签使用自定义格式函数,例如moment.js。类似于

    function myFormat(d) {
      return moment(d * 1000).fromNow();
    }
    

    【讨论】:

    • 谢谢!我用过: .tickFormat(function (d) { return moment.unix(d).fromNow(); }) 效果很好!
    猜你喜欢
    • 1970-01-01
    • 2013-03-06
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多