[Chartjs]-How to align count text center in horizontal bar in the Chart.js?

2👍

You can get the center position of each horizontal bar (inside meta.data loop) as follows :

var barWidth = bar._model.x - bar._model.base;
var centerX = bar._model.base + barWidth / 2;

and after getting the position, draw the count text accordingly…

Chart.helpers.each(this.data.datasets.forEach(function(dataset, i) {
   var meta = chartInstance.controller.getDatasetMeta(i);
   Chart.helpers.each(meta.data.forEach(function(bar, index) {
      var data = dataset.data[index];
      var barWidth = bar._model.x - bar._model.base;
      var centerX = bar._model.base + barWidth / 2;
      if (i == 0) {
         ctx.fillText(data, centerX, bar._model.y + 4);
      } else {
         ctx.fillText(data, centerX, bar._model.y + 4);
      }
   }), this);
}), this);

see – live demo

Leave a comment