使用d3.js在x轴上显示相对时间

Sco*_*ell 2 javascript d3.js nvd3.js

我正在尝试使用nvd3.js来显示随时间的评级(近乎实时;数据每3分钟更新一次).现在数据似乎正确显示,除了x轴显示的纪元时间不是很易读.如何让x轴显示"x Minutes Ago"而不是纪元时间?

这是我正在使用的代码:

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"
    }
  ];
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*off 6

对使用例如moment.js的标签使用自定义格式函数.有点像

function myFormat(d) {
  return moment(d * 1000).fromNow();
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我用过:.tickFormat(function(d){return moment.unix(d).fromNow();})它工作得很好! (3认同)