[Chartjs]-How to prevent tick labels from "jumping" when drawn with ChartJS BeforeDraw

5👍

Yes! there is a way. Use the following plugin :

plugins: [{
   beforeDraw: function(chart) {
      // hide original tick
      chart.scales['y-axis-0'].options.ticks.fontColor = 'transparent';
   },
   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 = 'rgba(0, 0, 0, 0.8)';
         ctx.fillText(tick, xPos - xPadding, yPos + tickGap / 2);
         ctx.restore();
      });
   }
}]

demo ⧩

var barChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Jan', 'Feb', 'Mar'],
      datasets: [{
         label: 'BAR',
         data: [10, 20, 30],
         backgroundColor: 'rgba(0, 119, 204, 0.5)'
      }]
   },
   options: {
      responsive: false,
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true,
               "userCallback": function(t, i) {
                  var mapping_function = ["", "Critical", "Needs Work", "Good", "Needs Work", "Getting There", "Great Choices"];
                  //return t;
                  return mapping_function[mapping_function.length - (i + 1)];
               },
            }
         }]
      }
   },
   plugins: [{
      beforeDraw: function(chart) {
         // hide original tick
         chart.scales['y-axis-0'].options.ticks.fontColor = 'transparent';
      },
      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 = 'rgba(0, 0, 0, 0.8)';
            ctx.fillText(tick, xPos - xPadding, yPos + tickGap / 2);
            ctx.restore();
         });
      }
   }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" height="200"></canvas>

Leave a comment