Chartjs-Trying to call API and plot a line chart but it does not show

0👍

The data property of individual datasets for a line chart can be passed in two formats, number[] or Point[]. Point[] is useful in the following cases:

  1. If the number of data points from individual datasets is different.
  2. if x-values of data points from different datasets are different.

In your case, if you specify data.labels, there’s no need to define the data of individual datasets as an array of Point.

Please have a look at your amended code below:

$.ajax({
  url: "https://api.thevirustracker.com/free-api?countryTimeline=PK",
  dataType: 'json',
  success: result => {
    const rawData = result.timelineitems[0];
    delete rawData.stat;
    const labels = Object.keys(rawData);
    const data = Object.values(rawData);
    
    var chart = new Chart(document.getElementById('myChart'), {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'New Daily Cases',
          data: data.map(o => o.new_daily_cases),          
          borderColor: "violet",
          fill: false
        },
        {
          label: 'New Daily Deaths',
          data: data.map(o => o.new_daily_deaths),          
          borderColor: "orange",
          fill: false
        },
        {
          label: 'Total Cases',
          data: data.map(o => o.total_cases),          
          borderColor: "blue",
          fill: false
        },
        {
          label: 'Total recoveries',
          data: data.map(o => o.total_recoveries),          
          borderColor: "green",
          fill: false
        },
        {
          label: 'Total Deaths',
          data: data.map(o => o.total_deaths),          
          borderColor: "red",
          fill: false
        }]
      },
      options: {}
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment