Chartjs-ChartJS – Time graph from JSON

2👍

There is an error in Date initialization:

new Date('2017,03,01')

should be replaced by

new Date(2017,03,01)

(without quotes), because ‘2017,03,01’ is a string with an invalid date format.
You can initialize a Date object with a string with the following format (the same you have as input):

 new Date('2017-03-01')

In order to trasform the json of your input you can write a function like this:

 var input = [{"y":4,"x":"2017-01-01"},
              {"y":0,"x":"2017-01-02"},
              {"y":9,"x":"2017-01-03"}, 
              {"y":0,"x":"2017-01-04"},
              {"y":14,"x":"2017-01-05"}];

 var data = input.map(function(item) {
      return {x: new Date(item["x"]), y: item["y"]};
 });

and pass data to your graph.

0👍

Use the json data as is, but tell chart.js that the x axis is time. working fiddle

options: {
 "scales": {
  "xAxes": [{
    "type": "time"
  }]
 }
}

See http://www.chartjs.org/docs/latest/axes/cartesian/time.html for more time axis configuration options. Especially the parser (tick) property, if using various time and date formats.

Leave a comment