【问题标题】:Bar Chart Not Stacking When Using ChartJs使用 ChartJs 时条形图不堆叠
【发布时间】:2021-02-23 06:48:04
【问题描述】:

我正在尝试使用 chartJs 创建堆积条形图(垂直或水平)。遵循他们的文档并在 SO 上尝试了各种解决方案,但我仍然无法将值堆叠起来。

const ctx = document.getElementById('chart-canvas').getContext('2d');
const chartCanvas = () => {
   
const chart = new Chart(ctx, {

    type: 'bar',
    // The data for our dataset
    data: {
        labels: ['a', 'b', 'c'],
        datasets: [{
            label: 'some title here',
            data: [49999,20000,35000], 
            backgroundColor: ['rgba(255, 99, 132, .5)','rgba(25, 99, 132, .5)','rgba(255, 9, 12, .5)'],
            borderColor:     ['rgb(255, 99, 132)','rgb(25, 99, 132)','rgb(255, 9, 12)'],
        }]
    },

    // Configuration options go here
    options: {
        scales: {
            xAxes: [{ stacked: true }],
            yAxes: [{ stacked: true }]
        },
        legend: {
            display: false,
        },
        maintainAspectRatio: false,
    }
});
}
chartCanvas()

我创建了一个小提琴https://jsfiddle.net/trig79/oxantepu/1/

感谢任何关于我哪里出错的指导

【问题讨论】:

    标签: chart.js


    【解决方案1】:

    仅当您使用多个数据集时,堆叠选项才有效。您可以将每个堆叠的值放在单独的数据集中,以便您可以堆叠它们。

    const ctx = document.getElementById('chart-canvas').getContext('2d');
    const chartCanvas = () => {
       
    const chart = new Chart(ctx, {
    
        type: 'bar',
        // The data for our dataset
        data: {
            labels: ['First Data'],
            datasets: [
                {
                    label: 'a',
                    data: [49999], 
                    backgroundColor: ['rgba(255, 99, 132'],
                    borderColor:     ['rgb(255, 99, 132)'],
                },
                {
                    label: 'b',
                    data: [20000], 
                    backgroundColor: ['rgba(25, 99, 132, .5)'],
                    borderColor:     ['rgb(25, 99, 132)'],
                },
                {
                    label: 'c',
                    data: [35000], 
                    backgroundColor: ['rgba(255, 9, 12, .5)'],
                    borderColor:     ['rgb(255, 9, 12)'],
                }
            ]
        },
    
        // Configuration options go here
        options: {
            scales: {
                xAxes: [{
                  stacked: true
                }],
                yAxes: [{
                  stacked: true
                }]
              },
            legend: {
                display: false,
            },
            maintainAspectRatio: false,
        }
    });
    }
    chartCanvas()
    

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2021-07-10
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 2020-10-20
      • 2023-01-31
      相关资源
      最近更新 更多