Chartjs to load an external json file and create a line chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Chartjs to load an external json file and create a line chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*w ww .  j a  va  2s  .c om*/
$(document).ready(function() {
  var labels = [];
  var dataXXX = [];
  var dataYYY = [];
  $.ajax({
    type: 'GET',
    url: 'https://api.myjson.com/bins/1igag',
    dataType: 'json',
    success: function(field) {
      for (var i = 0; i < field.length; i++) {
        labels.push(field[i].time);
        dataXXX.push(field[i].xxx);
        dataYYY.push(field[i].yyy);
      }
      var ctx = document.getElementById("myChart").getContext('2d');
      var myChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
              label: 'xxx',
              data: dataXXX,
              fill: false,
              backgroundColor: 'red',
              borderColor: 'red',
            },
            {
              label: 'yyy',
              data: dataYYY,
              fill: false,
              backgroundColor: 'green',
              borderColor: 'green',
            },
          ]
        },
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      });
    }
  });
})
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart" width="400" height="400"></canvas>  
   </body>
</html>

Related Tutorials