首页 > 解决方案 > 从 ChartsJs 创建一个不显示我希望它如何显示的堆叠组图

问题描述

我正在学习如何将 Chart.js堆叠条形图(带组)合并到我的应用程序中。

我正在使用 3 个数据集,其中一个堆叠在另一个之上,而第三个独立。我浏览了文档并尝试构建它,但是所有 3 组数据都堆叠在一起,这是我不想要的。

有人可以在下面查看我的脚本文件并让我知道可能出了什么问题吗?这是来自 Chart.js的repo的链接。如果您想查看我正在尝试构建的内容,请单击堆叠组图链接。

$(function () {
    new Chart(document.getElementById("line_chart").getContext("2d"), getChartJs('line'));
    new Chart(document.getElementById("stackedgroup_chart").getContext("2d"), getChartJs('stackedgroup'));
});


function getChartJs(type) {
    var config = null;

    if (type === 'line') {
        config = {
            type: 'line',
            data: {
                labels: ["January", "February", "March", "April", "May"],
                datasets: [{
                    label: "Refund",
                    data: [65, 59, 80, 45, 56],
                    borderColor: 'rgba(0, 188, 212, 0.75)',
                    backgroundColor: 'rgba(0, 188, 212, 0.3)',
                    pointBorderColor: 'rgba(0, 188, 212, 0)',
                    pointBackgroundColor: 'rgba(0, 188, 212, 0.9)',
                    pointBorderWidth: 1
                }
                ]
            },
            options: {
                responsive: true,
                legend: false
            }

        }
    }
    else if (type === 'stackedgroup') {
        config = {
            type: 'bar',
            data: {
                labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'],
                datasets: [{
                    label: 'Dataset 1',
                    backgroundColor: 'rgba(0, 188, 212, 0.8)',
                    stack: 'Stack 0',
                    data: [0, 10, -20, 30, 40, 50, 60, 70],
                }, {
                    label: 'Dataset 2',
                    backgroundColor: 'rgba(233, 30, 99, 0.8)',
                    stack: 'Stack 1',
                    data: [70, 60, 50, 40, 30, -20, 10, 0],
                }, {
                    label: 'Dataset 3',
                    backgroundColor: 'rgba(255, 209, 0, 0.8)',
                    stack: 'Stack 1',
                    data: [-30, 30, 30, 30, 30, 30, -30]
                }]
            },
            options: {
                title: {
                    display: true,
                    text: 'Stacked Group Chart'
                },
                tooltips: {
                    mode: 'index',
                    intersect: false
                },
                responsive: true,
                scales: {
                    xAxes: [{
                        stacked: true
                    }],
                    yAxes: [{
                        stacked: true
                    }]
                }

            }
        }
    }

    return config;
}

标签: javascriptchartschart.js

解决方案


推荐阅读