Chartjs-Fetching change-in stats from World Bank javascript JSON downloads using Chart.js

1đź‘Ť

Just a simple map to subtract each value with the previous value.
Checks to make sure values are number, if not it will return 0.

I added in filter for null gdps, so those years don’t show up in the chart. Note if there are “holes” in between, it’ll just use the last year available.

document.addEventListener('DOMContentLoaded', () => {
    // console.log("loaded")
    window.countrycode = 'US';
    window.indcode='NY.GDP.PCAP.PP.CD';
    fetchData()
})

function fetchData () {
    fetch('https://api.worldbank.org/v2/country/' + window.countrycode + '/indicator/' + window.indcode + '?format=json&per_page=120')
    .then(resp => resp.json())
    .then(data => {
        let years = data[1].map(year => year.date).reverse()
        let gdps = data[1].map(year => year.value).reverse()
        
        years = years.filter((x,i)=>gdps[i]!==null)
        gdps = gdps.filter(x=>x!==null)

        createChart(years,gdps)
        
        gdps = gdps.map((gdp,i)=> (
          (typeof gdp !== 'number' || typeof gdps[i-1] !== 'number') ? 0 :
          gdp-gdps[i-1]
        ))
        createChart2(years,gdps)
    })  

}

function createChart(years,gdps){
    new Chart(document.getElementById("line-chart"), {
        type: 'line',
        data: {
          labels: years,
          datasets: [{ 
              data: gdps,
              label: "USA GDP",
              fill: false,
              backgroundColor: 'blue',
              borderColor: 'blue',
              pointBorderColor: 'blue',
              pointRadius: 1,
            }   
          ]
        },
        options: {
          title: {
            display: false,
            text: 'USA GDP Data 1969 - 2019',
          },
          animation: false,
          legend: {display: true},
          maintainAspectRatio: false,
          responsive: true,
          responsiveAnimationDuration: 0,
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true,
                callback: function(value, index, values) {
                  if(parseInt(value) >= 1000){
                    return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                  } else {
                    return '$' + value;
                  }
                }
              }
            }]
          }
        }
      });
}
function createChart2(years,gdps){
  new Chart(document.getElementById("line-chart2"), {
      type: 'bar',
      data: {
        labels: years,
        datasets: [{ 
            data: gdps,
            // label: "USA GDP",
            fill: false,
            backgroundColor: 'blue',
            borderColor: 'blue',
            pointBorderColor: 'blue',
            pointRadius: 1,
          }   
        ]
      },
      options: {
        title: {
          display: false,
          text: 'USA GDP Data 1969 - 2019',
        },
        animation: false,
        legend: {display: true},
        maintainAspectRatio: false,
        responsive: true,
        responsiveAnimationDuration: 0,
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true,
              callback: function(value, index, values) {
                if(parseInt(value) >= 1000){
                  return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                } else {
                  return '$' + value;
                }
              }
            }
          }]
        }
      }
    });
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css">
<canvas id="line-chart" width="100%" height="250"></canvas>
 <canvas id="line-chart2" width="100%" height="145"></canvas>
 <!--<button type="button">Change js window.code values</button>-->
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

Leave a comment