Javascript 分组条形图,在 chart.js 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28180871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:20:14  来源:igfitidea点击:

Grouped bar charts, in chart.js

javascriptchart.js

提问by Jeff Dege

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.

我见过其他支持分组条形图的 javascript 图表库,如下图所示。在chart.js 的在线编辑器中,我没有将其视为显式选项。

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?

是否可以在 chart.js 中制作此类分组条形图?这简单吗?他们的在线编辑器中有模板吗?

回答by Jacob Budin

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

是的,您可以使用该datasets属性提供多个数据集,该属性是一个包含值分组的数组。每个数据集包含一系列data对应于 的值labels

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

根据您的 Chart.js 版本,请参阅下面两个略有不同的示例。



Chart.js v1.x

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.

看到这个 JSFiddle



Chart.js v2.x

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.

看到这个 JSFiddle