[Chartjs]-How to change x-Axes label position in Chart.js

3👍

You can change the xAxes label positions with the following steps:

  1. Add .getContext("2d") to the call that gets the ctx canvas object:

    var ctx = document.getElementById("gescanntePackzettelChart").getContext("2d");
    
  2. Hide the current xAxes ticks:

    xAxes: [{
        ticks: {
            display: false
        }
    }
    
  3. Add an animation to the options config, and use the canvas fillText() method to create new labels:

    animation: {
        duration: 1,
        onComplete: function() {
            var controller = this.chart.controller;
            var chart = controller.chart;
            var xAxis = controller.scales['x-axis-0'];
    
            var numTicks = xAxis.ticks.length;        
            var xOffsetStart = xAxis.width / numTicks;
            var halfBarWidth = (xAxis.width / (numTicks * 2));
    
            xAxis.ticks.forEach(function(value, index) {
                var xOffset = (xOffsetStart * index) + halfBarWidth;
                var yOffset = chart.height - 20;
                ctx.fillText(value, xOffset, yOffset);
            });
    
        }
    }
    

    For xOffset, to figure out the correct position, take the xAxis width and divide it by the number of tick labels. This will tell you how wide each bar is. Then, multiply that number by the current index to position the label in front of the correct bar. Finally, add add the width of half a bar to center the labels in the bar.

    For the yOffset, start with the chart’s height and subtract however much you want to move the labels up.

Working JSFiddle: https://jsfiddle.net/m5tnkr4n/124

0👍

Building on @Tot-Zam’s response, it’s possible to use the ChartJs scale object’s methods to define the context pixel coordinates easier. You also don’t need to define a ctx object – it is already accessible using the this.chart object.

    animation: {
          duration: 0,
          onComplete: function() {
            let chart = this.chart;
            let controller = chart.controller; 
            let axis = controller.scales['x-axis-0'];
            let yOffset = chart.height - 5;
            axis.ticks.forEach(function(value, index) {
              let xOffset = axis.getPixelForValue(value);     
              chart.ctx.fillText(value, xOffset, yOffset);
            })
          }
        }

Working repl: https://repl.it/@lunarplasma/ChartJs-custom-axis-labels

Leave a comment