Chartjs-Chart.js : How I change the x axes ticks labels alignment in any sizes?

4👍

The option you’re looking for is offsetGridLines.

If true, grid lines will be shifted to be between labels.

xAxes: [{
  ... 
  gridLines: {
    offsetGridLines: true
  }

In most cases, this produces the expected result. Unfortunately it doesn’t work for time axes as documented in Chart.js issue #403. Thanks to Antti Hukkanen, there exists a workaround.

Please have a look at below runnable code snippet to see how it works.

function generateData() {
  var unit = 'day';
  function randomNumber(min, max) {
    return Math.random() * (max - min) + min;
  }

  function randomPoint(date, lastClose) {
    var open = randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);
    var close = randomNumber(open * 0.95, open * 1.05).toFixed(2);
    return {
      t: date.valueOf(),
      y: close
    };
  }
    
  var date = moment().subtract(1, 'years');
  var now = moment();
  var data = [];
  for (; data.length < 600 && date.isBefore(now); date = date.clone().add(1, unit).startOf(unit)) {    
    data.push(randomPoint(date, data.length > 0 ? data[data.length - 1].y : 30));
  }
  return data;
}

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);

var cfg = {
  data: {
    datasets: [{
      label: 'CHRT - Chart.js Corporation',
      backgroundColor: 'red',
      borderColor: 'red',
      data: generateData(),
      type: 'line',
      pointRadius: 0,
      fill: false,
      lineTension: 0,
      borderWidth: 2
    }]
  },
  options: {
    animation: {
      duration: 0
    },
    scales: {
      xAxes: [{
        type: 'timecenter',
        time: {
          unit: 'month',
          stepSize: 1,
          displayFormats: {
            month: 'MMM'
          }
        },
        gridLines: {
          offsetGridLines: true
        }
      }],
      yAxes: [{
        gridLines: {
          drawBorder: false
        }
      }]
    },
    tooltips: {
      intersect: false,
      mode: 'index'
    }
  }
};
var chart = new Chart('chart1', cfg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart1" height="90"></canvas>

0👍

For chartJs v3 you can use offset property:

scales: {
  x: {
    grid: {
        offset: true
    }
  },
...
}

Leave a comment