Showing Chart.js Count/Numbers On Each Bar

While showing the bars using Chart.js, it usually shows the bar and lines but not the numbers, unless you hover. If you want to show the count or number on top of each bar, following code is what you can add.

Count / Numbers On Top Of Each Bar – Chart.js

As per the code where you want to show count or numbers on top of each bar, you need to add the following code right after hover (as below)
hover : {
        mode     : mode,
        intersect: intersect,
	animationDuration: 0
      },

animation: {
	duration: 1,
	onComplete: function () {
		var chartInstance = this.chart,
			ctx = chartInstance.ctx;
		ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
		ctx.textAlign = 'center';
		ctx.textBaseline = 'bottom';

		this.data.datasets.forEach(function (dataset, i) {
			var meta = chartInstance.controller.getDatasetMeta(i);
			meta.data.forEach(function (bar, index) {
				var data = dataset.data[index];                            
				ctx.fillText(data, bar._model.x, bar._model.y - 5);
			});
		});
	}
},

By adding the above code in green, you should be able to start seeing the numbers in each bar.

Dont forget to also add the line of animationDuration in hover as shown above in the code, to avoid the issue of blinking of the count while hovering.

Leave a Reply

Your email address will not be published. Required fields are marked *