[Chartjs]-Loading an external JSON into ChartJs

6๐Ÿ‘

โœ…

If you want to use the returned JSON from data.json you need to do this in the callback function like this:

$.getJSON("data.json", function (json) {
  // will generate array with ['Monday', 'Tuesday', 'Wednesday']
  var labels = json.map(function(item) {
    return item.timestamp;
  });

  var data = {
    labels: labels,
    datasets: [
    {
      label: "My First dataset",
      fillColor: "rgba(220,220,220,0.5)",
      strokeColor: "rgba(220,220,220,0.8)",
      highlightFill: "rgba(220,220,220,0.75)",
      highlightStroke: "rgba(220,220,220,1)",
      data: [65, 59, 80, 81, 56, 55, 40]
    },
    {
      label: "My Second dataset",
      fillColor: "rgba(151,187,205,0.5)",
      strokeColor: "rgba(151,187,205,0.8)",
      highlightFill: "rgba(151,187,205,0.75)",
      highlightStroke: "rgba(151,187,205,1)",
      data: [28, 48, 40, 19, 86, 27, 90]
    }
    ]
  };

  var ctx = document.getElementById("myChart").getContext("2d");
  ctx.canvas.width = 1000;
  ctx.canvas.height = 800;

  var myChart = new Chart(ctx).Bar(data);
});

If you are using it with Angular I would recommend using the angular chart.js version, see: http://jtblin.github.io/angular-chart.js/

Then you already have an angular directive, which you can use!

Leave a comment