Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - Grouped bar charts, in chart.js

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 online editor.

Is it possible to do grouped bar charts of this sort in chart.js? Is it easy? Is there a template for it in their online editor?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...