سؤال

I'm trying to use nvd3.js to display ratings over time (in near real time; the data updates every 3 minutes). Right now the data appears to be showing correctly except the x-axis displays epoch time which isn't very readable. How can I have the x-axis display "x Minutes Ago" rather than the epoch time?

Here is the code that I am using:

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"
    }
  ];
}
هل كانت مفيدة؟

المحلول

Use a custom format function for the labels that uses e.g. moment.js. Something along the lines of

function myFormat(d) {
  return moment(d * 1000).fromNow();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top