Chartjs-Chart.js V4.3.0 X-Axis Labels Not Aligning

1πŸ‘

βœ…

I think the align option is working as designed. The position where the option is applied is related to the middle of the "tick". It’s implemented as textAlign property of Context2D https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/textAlign

You can change the position of the ticks by a custom plugin:

const p = {
  id: 'my',
  beforeDraw(chart) {
    const scale = chart.scales.x;
    const items = scale.getLabelItems();
    const {data} = chart.getDatasetMeta(0);
    for (let i=0; i<items.length; i++) {
      const {x, width} = data[i];
      const newX = x - width / 2;
      items[i].options.translation.splice(0, 1, newX);
    }
  },  
}

You should add the plugin

new Chart(ctx, {
  type: 'bar',
  plugins: [p],
  data: {
  ...

and then set align option to the X scale ticks to 'start'.

Codepen: https://codepen.io/stockinail/pen/qBQWxZQ

Leave a comment