ArticleZip > Show Values On Top Of Bars In Chart Js

Show Values On Top Of Bars In Chart Js

Have you ever wanted to enhance your Chart.js visualizations by displaying values directly on top of each bar? It's a common feature that can make your charts more informative and engaging for your audience. In this guide, I'll show you how to easily implement this neat addition to your bar chart using Chart.js, a popular and versatile JavaScript library for creating interactive data visualizations.

First, ensure you have Chart.js set up in your project. If you haven't included it yet, you can easily do so by either downloading the library from the official Chart.js website or by linking directly to a CDN-hosted version. Once you have Chart.js integrated, you're ready to start customizing your bar chart.

To display values on top of the bars in your Chart.js chart, you can leverage the "onRender" callback function. This function allows you to access each bar on your chart and add custom text or graphics. In this case, we'll be adding the actual values on top of each bar.

Here's how you can achieve this:

1. Define the onRender callback function:

Javascript

Chart.plugins.register({
  afterDatasetsDraw: function(chart) {
    var ctx = chart.ctx;

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

2. Attach the onRender callback to your chart:

Javascript

var myBarChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: {
    responsive: true,
    onRender: function(e) {
      // Implement the onRender logic here
    }
  }
});

In the provided code snippet, we've implemented the onRender callback function to iterate through each dataset on the chart, retrieving the data associated with each bar and drawing it directly on top of the bar. Adjust the positioning and styling of the displayed values as needed to suit your design preferences.

And that's it! By following these simple steps, you can now effortlessly show values on top of the bars in your Chart.js bar chart, making your visualizations more informative and engaging for your audience. Experiment with different customization options to further enhance the appearance and functionality of your charts. Happy coding!

×