Reputation: 335
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:
Someone could teach me how to do that?
Thank you.
Upvotes: 22
Views: 32126
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
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
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