简体   繁体   中英

How to display grouped data in ChartJs

I have the following array:

在此处输入图片说明

Where the arrays keys are the dates and the only element I want to plot, of each set, is the weight. Look:

在此处输入图片说明

I am putting the code as follows. Notice that I am already grouping in the date attribute the whole set belonging to each that key.

var ctx = document.getElementById("barChart").getContext("2d");

var data = {
    labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
    datasets: [
        {
            label: '21/03/2018',
            data: [12, 0, 0]
        },
        {
            label: '01/04/2018',
            data: [15.00, 15.00,15.00]
        },
        {
            label: '02/04/2018',
            data: [25.00, 25.00, 25.00]
        },
        {
            label: '04/04/2018',
            data: [25.00, 25.00, 25.00]
        },
        {
            label: '05/04/2018',
            data: [-8.14,-7.93, -7.84]
        },
        {
            label: '06/04/2018',
            data: [-35.9 ,-38.1, -37.5]
        },
    ]
};

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
});

But in this way ChartJs does not understand that it only needs to plot the data set present in the "data" attribute and grouping them by the key. Plotting the graph in the wrong way.

在此处输入图片说明

How could I plot the data correctly knowing that they are already grouped?

You need to organize your data as such:

var ctx = document.getElementById("canvas").getContext("2d");

var data = {
    labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
    datasets: [
        {              
                data: [12, 15.00, 25.00, 25.00, -8.14, -35.9]
        },{          
                data: [0, 15.00, 25.00, 25.00, -7.93, -38.1]
        },{          
                data: [0, 15.00, 25.00, 25.00, -7.84, -37.5]
        }
    ]   
};

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options:{
        legend: 'none'
    }
});

I took your legend out as it's useless in this case. To look at it in the coding persepective, whatever index the date in labels is at needs to correlate with the index of the information you want to display in that grouping. data[0] refers to labels[0] and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM