[Chartjs]-CHART.JS How can I offset/move/adjust the labels on the y-axis to be in the middle of the gridlines instead of centered on the gridlines?

5👍

I’ve annotated the changes in the below snippet, but to briefly explain:

I integrated the plugin you linked to but modified it to set the original ticks to transparent and therefore removed the beforeDraw closure which didn’t seem to work.

For bonus points: the trick is to remove the x-axis border and then style the ‘zero line’ to match the other grid lines.

var ctx = document.getElementById("chart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
    datasets: [{
      data: [25, 35, 20, 45, 65, 26, 49, 70, 75, 87],
      borderColor: 'white',
      fill: false
    }]
  },
  options: {
    legend: {
      display: false
    },
    scaleShowVerticalLines: false,
    layout: {
      padding: 25
    },
    scales: {
      xAxes: [{
        gridLines: {
          display: false,
          drawBorder: false, // bonus points.
        },
        ticks: {
          display: false
        }
      }],
      yAxes: [{
        gridLines: {
          drawBorder: false,
          color: 'rgba(0,0,0,.3)', // bonus points.
          zeroLineColor: 'rgba(0,0,0,.3)' // bonus points.
        },
        ticks: {
          min: 0,
          max: 100,
          stepSize: 25,
          fontColor: 'transparent', // changed from 'white'
          callback: function(value) {
            if (value === 25) {
              return 'Red';
            } else if (value === 50) {
              return 'Orange';
            } else if (value === 75) {
              return 'Yellow';
            } else if (value === 100) {
              return 'Green';
            } else {
              return '';
            }
          }
        }
      }]
    }
  },
  plugins: [{
    afterDraw: function(chart) {
      var ctx = chart.ctx;
      var yAxis = chart.scales['y-axis-0'];
      var tickGap = yAxis.getPixelForTick(1) - yAxis.getPixelForTick(0);
      // loop through ticks array
      Chart.helpers.each(yAxis.ticks, function(tick, index) {
        if (index === yAxis.ticks.length - 1) return;
        var xPos = yAxis.right;
        var yPos = yAxis.getPixelForTick(index);
        var xPadding = 10;
        // draw tick
        ctx.save();
        ctx.textBaseline = 'middle';
        ctx.textAlign = 'right';
        ctx.fillStyle = 'white';
        ctx.fillText(tick, xPos - xPadding, yPos + tickGap / 2);
        ctx.restore();
      });
    }
  }]
});
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart" style="background-color:#296390"></canvas>

Leave a comment