How to show data values or index labels in ChartJs (Latest Version)

て烟熏妆下的殇ゞ 提交于 2019-11-29 02:45:30

Finally I got it working.

Used the following code in the onComplete() function:

animation: {
    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);
                }
            }
        });
    }
}

Got it to work after some researching.

You have to set it after in the onComplete event of the animation. The x, y values of the bars are stored in the model of the children (point, line, bar, whatever)

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

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

Just the structure changed a little bit.

You can see it in this working JSFiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!