简体   繁体   English

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

[英]How to display different datasets from different ajax calls in the same ChartJS?

I'm trying to display different datasets, from different ajax calls, in the same chartJS.我正在尝试在同一个 chartJS 中显示来自不同 ajax 调用的不同数据集。 The idea is to show different stats per month, on 13 consecutive months.这个想法是在连续 13 个月内每月显示不同的统计数据。 1 ajax call = 1 stat for each of the 13 months. 1 ajax 调用 = 13 个月中每个月的 1 个统计数据。 The JSON data for on stat looks like this: stat 的 JSON 数据如下所示:

[{"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}] [{"month":"June 2020","value":0},{"month":"May 2020","value":0},{"month":"April 2020","value":0 },{"month":"2020 年 3 月","value":0},{"month":"2020 年 2 月","value":30},{"month":"2020 年 1 月","value": 182},{"月":"2019 年 12 月","值":143},{"月":"2019 年 11 月","值":111},{"月":"2019 年 10 月","值" :103},{"month":"September 2019","value":128},{"month":"August 2019","value":71},{"month":"July 2019","value ":129},{"月":"2019 年 6 月","值":98}]

Of course, the values determinate the bars, and the months are the chart's labels.当然,值决定了条形,月份是图表的标签。 I can display one stat for every month, but I can't add the others (3 more stats to show).我可以每个月显示一个统计信息,但我不能添加其他统计信息(要显示另外 3 个统计信息)。 The expected result: 4 bars for each month.预期结果:每月 4 条。 Here is my working code for one dataset:这是我的一个数据集的工作代码:

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?如何添加其他3个? Any help would be appreciated.任何帮助,将不胜感激。 Thanks a lot !非常感谢 !

Let's suppose you fetched your data and have multiple statistics/arrays containing the data for each month.假设您获取了数据并有多个包含每个月数据的统计信息/数组。

You can compute a lookup that maps the month to the values of the different statistics.您可以计算将月份映射到不同统计数据的值的查找。

The labels are simply the keys, although you'd probably want to sort them based on the date.标签只是键,尽管您可能希望根据日期对它们进行排序。 The datasets can easily be computed by mapping the labels.通过映射标签可以轻松计算数据集。

 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>

I have finally succeeded, based on Martin M.'s idea.基于 Martin M. 的想法,我终于成功了。 Here is my code (maybe it can help someone who has the same issue).这是我的代码(也许它可以帮助有同样问题的人)。 It works perfectly.它完美地工作。

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

Thank you all for your help !谢谢大家的帮助 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM