javascript - 使用 Chart.js 从世界银行 javascript JSON 下载中获取变化统计数据

标签 javascript arrays json chart.js fetch

这是 user120242 建议的更新脚本和解决方案,用于计算世界银行数据下载的统计数据变化。我在这里展示了他的工作脚本,其中进行了一些调整,允许 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> 

最佳答案

只是一个简单的映射,用于将每个值与前一个值相减。 检查以确保值是数字,如果不是,则返回 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>

关于javascript - 使用 Chart.js 从世界银行 javascript JSON 下载中获取变化统计数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61552006/

相关文章:

android - 是否可以将 Realm 对象转换为 JSON 对象?

javascript - 具有动态数据的 HighCharts 不起作用

javascript - 调整大小时如何更新包装内容div?

python - 展平包含不同形状的 numpy 数组的列表

c# - 将字节从文本框转换为字节数组再转换为字符时的奇怪行为?

java - 如何在 Java Android 中共享/导出 JSON 文件

php - 如何将编码的 JSON 字符串返回给 jQuery 调用?

javascript - 在 chrome 扩展中使用 html5 blob 下载文件

javascript - Angular 11 与 Webpack 5 - 向 IE11 用户显示消息

java - 如何使用 Arrays.sort 对 java 中的二维字符串数组中的每一行进行排序?