Search code examples
javascriptchartsalignment

How to align X-Axis ticks on vertical gridlines (Chart.js, Bar-Chart)


I would like to align the X-axis label exactly on the vertical gridlines and not in between. In a line chart this is active by default.

Is the align option not applicable for bar charts? common-tick-options-to-all-cartesian-axes Or am I doing something wrong?

    var options = {
    type: 'bar',
    data: {
      labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
      datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        },
        x: {
          ticks: {
            align: 'start'
        },
        }
      },
      events: []
    }
  }

My example on jsfiddle

What i want: enter image description here


Solution

  • I was able to solve it by setting the labelOffset dynamically through an ChartJs-API call.

    let myChart = new Chart(ctx, options);    
    const visibleMetas = myChart.getSortedVisibleDatasetMetas();
    let offset = visibleMetas[0].data[0].width / 2
    myChart.options.scales.x.ticks.labelOffset = -offset;
    myChart.update();
    

    https://jsfiddle.net/Syncd/8z6rm9ck/