[Chartjs]-Chartjs show 24 hours in line chart

2👍

Since you did not provide how you initialize the chartjs plugin, assume you have this configuration of line chart, the labels are date that shown on the x-axis, label is the chart name shown on top, and the data is the sum of the count that will be calculated.

var dataset = [{
    "hour": "2018-03-18T00:00:00.000Z",
    "count": 230
    }, {
    "hour": "2018-03-18T04:00:00.000Z",
    "count": 450
}];

// group the dataset by date

var dataGroup = [];  // array of { date : count } 
for (var idx in dataset) {
    var date = dataset[idx]['hour'].substr(0, 10);
    dataGroup[date] = dataGroup[date] || 0;
    dataGroup[date] += dataset[idx]['count'];
}

var labels = []; // labels shown on the x-axis
var data = []; // sum of count group by date
for (var date in dataGroup) {
    labels.push(date);
    data.push(dataGroup[date]);
}

var ctx = document.getElementById("chart").getContext("2d");
new Chart(ctx, {
    type: 'line',
    data: {
        labels: labels,
        datasets: [
            label: label,
            data: data,
            fillColor: "#79D1CF",
            strokeColor: "#79D1CF",
        ]
    }
});

Leave a comment