[Chartjs]-ChartJS – Draw chart with label by month, data by day

12👍

Just config your xAxes->time property as:
unit: ‘month’

xAxes: [{
  type: 'time',
  position: 'bottom',
  time: {
    displayFormats: {'day': 'MM/YY'},
    tooltipFormat: 'DD/MM/YY',
    unit: 'month',
   }
}],

0👍

The labels array and the data array have to match.
Therefore what you will need to do is calculate your values to be hold in data array in to match your labels

data: {
    labels: ["Jan", "Feb", "March", ...],
    datasets: [{
        label: '# of Votes',
        data: [01, 02, 03, ...],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            ...
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            ...
        ],
        borderWidth: 1
    }]
},

Does that solve your doubt?

0👍

This question is quite old now, but I have found a workaround using the afterTickToLabelConversion functionnality. I formatted the date, and left only one label for every month (the rest of the labels are transformed to empty quotes).
Here is the snippet to put in your graph option :

scales: {
        xAxes: [{
            type: 'time',
            position: 'bottom',
            time: {
                displayFormats: {
                    'day': 'MM/YY'
                },
                tooltipFormat: 'DD/MM/YY',
                unit: 'day',
            },
            // leave only one label per month
            afterTickToLabelConversion: function (data) {
                var xLabels = data.ticks;
                var oldLabel = "";
                xLabels.forEach(function (labels, i) {
                    if(xLabels[i] == oldLabel){
                        xLabels[i] = "";
                    } else {
                        oldLabel = xLabels[i];
                    }
                });
            }
        }]
    }

Leave a comment