0

As per chartjs version has changed,The dataset values display on bar itself has not working.The existing code has working with V1.0.2. Ref: how to display data values on Chart.js

var ctx = document.getElementById("myChart2").getContext("2d");
var myBar = new Chart(ctx).Bar(chartData, {
    showTooltips: false,
    onAnimationComplete: function () {

        var ctx = this.chart.ctx;
        ctx.font = this.scale.font;
        ctx.fillStyle = this.scale.textColor
        ctx.textAlign = "center";
        ctx.textBaseline = "bottom";

        this.datasets.forEach(function (dataset) {
            dataset.bars.forEach(function (bar) {
                ctx.fillText(bar.value, bar.x, bar.y - 5);
            });
        })
    }
});

Now what will be modification which must work with ChartJs V2.1.6? The current bar graph syntax has working with V2.1.6 given below.

        var myBarChart = new Chart(ctx, {
            type: 'bar',
            data: datasets,
            options: {
                responsive: true,
                tooltips: {
                    enabled: false
                },
                legend: {
                    display: false
                },
              //what should add to display values on bar?
            }
        });
Community
  • 1
  • 1
Amit Sah
  • 21
  • 5

1 Answers1

0

By using the animation.onComplete key, as follows:

animation: {
        duration: 500,
        onComplete: function() {
            var ctx = this.chart.ctx;
            ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
            ctx.fillStyle = "black";
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';

            this.data.datasets.forEach(function(dataset) {
                for (var i = 0; i < dataset.data.length; i++) {
                    for (var key in dataset._meta) {
                        var model = dataset._meta[key].data[i]._model;
                        ctx.fillText(dataset.data[i], model.x, model.y - 5);
                    }
                }
            });
        }
    }

http://www.chartjs.org/docs/#chart-configuration-animation-configuration

chafreaky
  • 90
  • 2
  • 7