[Chartjs]-Chart.js display x axis labels ON ticks in bar chart, not between

2👍

You can draw the tick lables at the desired position directly on to the canvas using the Plugin Core API. It offers number of hooks that may be used for performing custom code. In below code snippet, I use the afterDraw hook to draw my own labels on the xAxis.

const hours = ['00', '01', '02', '03', '04', '05', '06'];
const values = [0, 0, 0, 0, 10, 6, 0];

const chart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  plugins: [{
    afterDraw: chart => {      
      var xAxis = chart.scales['x-axis-0'];
      var tickDistance = xAxis.width / (xAxis.ticks.length - 1);
      xAxis.ticks.forEach((value, index) => {
        if (index > 0) {
          var x = -tickDistance + tickDistance * 0.66 + tickDistance * index;
          var y = chart.height - 10;
          chart.ctx.save();        
          chart.ctx.fillText(value == '0am' ? '12am' : value, x, y);
          chart.ctx.restore();
        }
      });      
    }
  }],
  data: {
    labels: hours,
    datasets: [{
      label: 'Dataset 1',
      data: values,
      categoryPercentage: 0.99,
      barPercentage: 0.99,
      backgroundColor: 'blue'
    }]
  },
  options: {
    responsive: true,
    legend: {
      display: false
    },   
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          parser: 'HH',
          unit: 'hour',
          displayFormats: {
            hour: 'Ha'
          },
          tooltipFormat: 'Ha'
        },
        gridLines: {
          offsetGridLines: true
        },
        ticks: {
          min: moment(hours[0], 'HH').subtract(1, 'hours'),
          fontColor: 'white'
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>

Leave a comment