close

how to display data values on Chart.js

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn how to display data values on Chart.js in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

how to display data values on Chart.js ?

  1. how to display data values on Chart.js ?

    display data values on Chart.js From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script> tag after the chart.js tag on your page), your charts begin to display values.

  2. display data values on Chart.js

    display data values on Chart.js From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script> tag after the chart.js tag on your page), your charts begin to display values.

Method 1

I think the nicest option to do this in chartJS v2.x is by using a plugin, so you don’t have a large block of code in the options. In addition, it prevents the data from disappearing when hovering over a bar.

I.e. simply use this code, which registers a plugin that adds the text after the chart is drawn.

Chart.pluginService.register({
    afterDraw: function(chartInstance) {
        var ctx = chartInstance.chart.ctx;

        // render the value of the chart above the bar
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';

        chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
                var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
                ctx.fillText(dataset.data[i], model.x, model.y - 2);
            }
        });
  }
});

Method 2

From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script> tag after the chart.js tag on your page), your charts begin to display values.

If you then choose you can customize it to fit your needs. The customization is clearly documented here but basically, the format is like this hypothetical example:

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: yourDataObject,
    options: {
        // other options
        plugins: {
            datalabels: {
                anchor :'end',
                align :'top',
                // and if you need to format how the value is displayed...
                formatter: function(value, context) {
                    return GetValueFormatted(value);
                }
            }
        }
    }
});

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment