Skip to content

Instantly share code, notes, and snippets.

@ahukkanen
Last active May 17, 2020 07:56
Show Gist options
  • Save ahukkanen/fe69a70c3708b32210fd18860ba609c5 to your computer and use it in GitHub Desktop.
Save ahukkanen/fe69a70c3708b32210fd18860ba609c5 to your computer and use it in GitHub Desktop.
Year label center alignment with Chart.js
// Initialization of the Chart using the defined scale type
var labels = [
'2015-01-01',
'2015-02-01',
'2015-03-01',
'2015-04-01',
'2015-05-01',
'2015-06-01',
// ...continue for 60 months in total for 5 years
];
var data = [
100,
110,
120,
150,
130,
100,
// ...continue for 60 months in total for 5 years
];
var datasets = [{
label: 'Data',
data: data,
fill: false,
lineTension: 0,
pointRadius: 0
}];
var ctx = document.getElementById('#chart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: datasets
},
options: {
responsive: true,
maintainAspectRatio: false,
legend: {
position: 'top'
},
scales: {
xAxes: [{
type: 'timecenter',
time: {
unit: 'year',
stepSize: 1
},
gridLines: {
offsetGridLines: true
},
maxTicksLimit: 4
}]
}
}
});
// Relevant part
// Override the getPixelForTick() from the original time scale.
var TimeCenterScale = Chart.scaleService.getScaleConstructor('time').extend({
getPixelForTick: function(index) {
var ticks = this.getTicks();
if (index < 0 || index >= ticks.length) {
return null;
}
// Get the pixel value for the current tick.
var px = this.getPixelForOffset(ticks[index].value);
// Get the next tick's pixel value.
var nextPx = this.right;
var nextTick = ticks[index + 1];
if (nextTick) {
nextPx = this.getPixelForOffset(nextTick.value);
}
// Align the labels in the middle of the current and next tick.
return px + (nextPx - px) / 2;
},
});
// Register the scale type
var defaults = Chart.scaleService.getScaleDefaults('time');
Chart.scaleService.registerScaleType('timecenter', TimeCenterScale, defaults);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment