[Chartjs]-Change position of Chart.js tick labels

8๐Ÿ‘

โœ…

You can change the position of the tick labels, and get the graph to look like your second image, by adding a few options to the configuration.

First, hide the yAxes and xAxes grid lines and tick labels with the following code:

gridLines: {
    display: false,
    drawBorder: false //hide the chart edge line
},
ticks: {
    display: false
}

Then, based off the idea shown here, use the following animation code to add the bar._model.label to on top of the bar:

animation: {
  duration: 1,
  onComplete: function() {
    var chartInstance = this.chart;

    ctx.font = Chart.helpers.fontString(16, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);

    this.data.datasets.forEach(function(dataset, i) {
      var meta = chartInstance.controller.getDatasetMeta(i);
      meta.data.forEach(function(bar, index) {

        var label = bar._model.label;
        var xOffset = 10;
        var yOffset = bar._model.y - 42;
        ctx.fillText(label, xOffset, yOffset);
      });
    });
  }
}

Animation JSFiddle Demo: https://jsfiddle.net/actxg695/1/


If you are okay with the labels showing on the bar, instead of on top of the bar, instead of hiding the ticks and using animation, you can just flip the tick labels over the yAxes using mirror:true:

ticks: {
    mirror: true,
    fontSize: 16, //make the font slightly larger
    padding: -10 //move the text slightly away from the bar edge
}

Mirror JSFiddle Demo: https://jsfiddle.net/actxg695/2/

-1๐Ÿ‘

If you are okay with the labels showing on the bar, instead of on top of the bar, instead of hiding the ticks and using animation, you can just flip the tick labels over the yAxes using mirror:true:

animation: {
  duration: 1,
  onComplete: function() {
    var chartInstance = this.chart;

    ctx.font = Chart.helpers.fontString(16, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);

    this.data.datasets.forEach(function(dataset, i) {
        var meta = chartInstance.controller.getDatasetMeta(i);

        meta.data.forEach(function(bar, index) {
            var label = bar._model.label;
            var xOffset = 10;
            var yOffset = bar._model.y - 42;
            ctx.fillText(label, xOffset, yOffset);
        });
    });
  }
}

Leave a comment