user4557573
user4557573

Reputation: 335

ChartJS - Draw chart with label by month, data by day

I'd like to draw a line chart by Chartjs with data by day, but label by month.

If label is displayed by day, then there are a lot of points. So, I'd like to display label by month instead of by day. For example:

enter image description here

Someone could teach me how to do that?

Thank you.

Upvotes: 22

Views: 32126

Answers (3)

David Merino
David Merino

Reputation: 131

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',
   }
}],

Upvotes: 11

eflamm
eflamm

Reputation: 1

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];
                    }
                });
            }
        }]
    }

Upvotes: 0

emerson-pereira
emerson-pereira

Reputation: 1

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?

Upvotes: 0

Related Questions