如何在同一个ChartJS中显示来自不同ajax调用的不同数据集?

问题描述 投票:0回答:1

我想在同一个ChartJS中显示不同的数据集,来自不同的ajax调用,我的想法是每个月显示不同的统计数据,连续13个月,1个ajax调用=13个月中每个月的1个统计数据。

[{"月份":"2020年6月","值":0},{"月份":"2020年5月","值":0},{"月份":"2020年4月","值":0},{"月份":"2020年3月","值":0},{"月份":"2020年2月","值":30},{"月份":"2020年1月","值":182},{"月份":"2019年12月","值"。 143},{"月":"2019年11月", "值":111},{"月":"2019年10月", "值":103},{"月":"2019年9月", "值":128},{"月":"2019年8月", "值":71},{"月":"2019年7月", "值":129},{"月":"2019年6月", "值":98}]

当然,数值决定了条形图,而月份是图表的标签.我可以显示每个月的一个统计,但我不能添加其他的统计(3个更多的统计显示).预期的结果:每个月4个条形图.这是我的一个数据集的工作代码。

function getJsonDataForStat1() {
    return $.ajax
    ({
        url: 'getJsonDataForStat1',
        type: 'get'
    });
}


function setChart() {
    $.when(getJsonDataForStat1()).done(function (stats) {

        stats = JSON.parse(stats);
        var data = [], labels = [];

        stats.forEach(function (s) {
            labels.push(s.month);
            data.push(s.value);
        });

        var ctx = document.getElementById('graph').getContext('2d');

        var graph = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'stat 1',
                        data: data,
                        backgroundColor: '#735288',
                        borderColor: '#3c8dbc',
                        borderWidth: 1
                    }],
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            }
        });
    });
}

How to add the 3 others ?A Any help would be appreciated. 非常感谢!

javascript json ajax chart.js
1个回答
0
投票

假设你获取了你的数据,并且有多个包含每个月数据的statisticsarrays。

你可以计算一个查找,将月份映射到不同统计的值。

标签就是简单的键,尽管你可能想根据日期对它们进行排序。通过映射标签,可以很容易地计算出数据集。

var lkp = [stat1, stat2].flat().reduce((acc, cur) => {
  const {
    month,
    value
  } = cur;
  acc[month] = acc[month] || [];
  acc[month].push(value);
  return acc;
}, {});

//{'June 2020': [0, 10], ...}

var labels = Object.keys(lkp).sort((a, b) => (Date.parse(a) % (1000 * 60 * 60 * 24 * 365)) - (Date.parse(b) % (1000 * 60 * 60 * 24 * 365)))
// ['June 2020', 'May 2020']

var colors = ['red', 'green'];

var datasets = [0, 1].map((index) => {
  const data = labels.map(label => lkp[label][index]);
  return {
    data,
    label: `Statistic ${index}`,
    backgroundColor: colors[index],
  }
});

var options = {
  type: 'bar',
  data: {
    labels,
    datasets,
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

var ctx = document.getElementById('chart').getContext('2d');

try {
  new Chart(ctx, options);
} catch (e) {
  //catch co error
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<script>
var stat1 = [{"month":"June 2020","value":0},{"month":"May 2020","value":0},{"month":"April 2020","value":0},{"month":"March 2020","value":0},{"month":"February 2020","value":30},{"month":"January 2020","value":182},{"month":"December 2019","value":143},{"month":"November 2019","value":111},{"month":"October 2019","value":103},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value":129},{"month":"June 2019","value":98}]
var stat2 = [{"month":"June 2020","value":10},{"month":"May 2020","value":25},{"month":"April 2020","value":75},{"month":"March 2020","value":80},{"month":"February 2020","value":30},{"month":"January 2020","value":182},{"month":"December 2019","value":23},{"month":"November 2019","value":123},{"month":"October 2019","value":50},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value":129},{"month":"June 2019","value":98}];

</script>
<canvas id="chart" width="600" height="400"></canvas>

0
投票

根据Martin M.的想法,我终于成功了,这是我的代码(也许它可以帮助有同样问题的人),它工作得很完美。

var graph = setChart();
updateChart();

function setChart() {
    $.when(getData1()).done(function (stats) {

        stats = JSON.parse(stats);

        var data = [], labels = [];

        stats.forEach(function (s) {
            labels.push(s.month);
            data.push(s.value);
        });

        var ctx = document.getElementById('graph').getContext('2d');

        return graph = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'data 1',
                        data: data,
                        backgroundColor: '#00c0ef',
                    }],
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            }
        });
    });
}


function updateChart() {
    $.when(setChart()).done(function () {

// I've repeated the following block for data 3 and 4 (still inside updateChart())
        $.when(getData2()).done(function (stats) {

            stats = JSON.parse(stats);
            var data = [];

            stats.forEach(function (s) {
                data.push(s.value);
            });

            var dataset = {};
            dataset.label = "data 2";
            dataset.backgroundColor = '#061834';
            dataset.data = data;

            graph.data.datasets.push(dataset);
            graph.update();
        })
    })
}

谢谢大家的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.