Извлечение статистики изменений из загрузок Всемирного банка javascript JSON с использованием диаграммы. js - PullRequest
0 голосов
/ 02 мая 2020

Это обновленный сценарий и решение, предложенное пользователем 120242 для расчета изменения статистики из загрузок данных Всемирного банка. Здесь я показываю его рабочий сценарий с рядом корректировок, позволяющих: 1) отображать пробелы в данных - или нет, 2) отображать значения или проценты изменений

Год-год второго графика имеет изменение нуля, и все после этого является дельтой между стоимостью этого года - и прошлогодней.

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()       

    createChart(years,gdps)
    
    years2 = years.filter((x,i)=>gdps[i]!==null)
    gdps2 = gdps.filter(x=>x!==null)
    gdps3 = gdps2.map((gdp,i)=> (
      (typeof gdp !== 'number' || typeof gdps2[i-1] !== 'number') ? 0 :
      gdp-gdps2[i-1]
    ))
    gdps4 = gdps2.map((gdp2,i2)=> (
      (typeof gdp2 !== 'number' || typeof gdps2[i2-1] !== 'number') ? 0 :
      (gdp2-gdps2[i2-1])/gdps2[i2-1]*100
    ))
    // console.log('Years:',years,'gdps:', gdps,'gdps2:', gdps2, 'gdps3:', gdps3, 'gdps4:', gdps4)
    createChart2(years2,gdps4)
    })  

}

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(years2,gdps4){
  new Chart(document.getElementById("line-chart2"), {
      type: 'bar',
      data: {
        labels: years2,
        datasets: [{ 
            data: gdps4,
            // 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) {
                    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> 

1 Ответ

1 голос
/ 02 мая 2020

Просто простая карта для вычитания каждого значения с предыдущим значением. Проверяет, чтобы убедиться, что значения являются числами, в противном случае он вернет 0.

Я добавил в фильтр для null gdps, поэтому эти годы не отображаются на графике. Обратите внимание, что если между ними есть «дыры», он будет использовать только последний доступный год.

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>
...