Grouped bar charts, in chart.js

后端 未结 1 1831
孤城傲影
孤城傲影 2020-12-08 01:47

I\'ve seen other javascript charting libraries that supported grouped barcharts, of the sort in the image below. I\'ve not seen this as an explicit option in chart.js\'s onl

相关标签:
1条回答
  • 2020-12-08 02:29

    Yes, you can provide multiple data sets using the datasets property, which is an array of containing groupings of values. Each data set contains a series of values in data that correspond to the labels.

    See two slightly different examples below depending on your version of Chart.js.


    Chart.js v1.x

    var ctx = document.getElementById("myChart").getContext("2d");
    
    var data = {
        labels: ["Chocolate", "Vanilla", "Strawberry"],
        datasets: [
            {
                label: "Blue",
                fillColor: "blue",
                data: [3,7,4]
            },
            {
                label: "Red",
                fillColor: "red",
                data: [4,3,5]
            },
            {
                label: "Green",
                fillColor: "green",
                data: [7,2,6]
            }
        ]
    };
    
    var myBarChart = new Chart(ctx).Bar(data, { barValueSpacing: 20 });
    

    See this JSFiddle.


    Chart.js v2.x

    var ctx = document.getElementById("myChart").getContext("2d");
    
    var data = {
        labels: ["Chocolate", "Vanilla", "Strawberry"],
        datasets: [
            {
                label: "Blue",
                backgroundColor: "blue",
                data: [3,7,4]
            },
            {
                label: "Red",
                backgroundColor: "red",
                data: [4,3,5]
            },
            {
                label: "Green",
                backgroundColor: "green",
                data: [7,2,6]
            }
        ]
    };
    
    var myBarChart = new Chart(ctx, {
        type: 'bar',
        data: data,
        options: {
            barValueSpacing: 20,
            scales: {
                yAxes: [{
                    ticks: {
                        min: 0,
                    }
                }]
            }
        }
    });
    

    See this JSFiddle.

    0 讨论(0)
提交回复
热议问题