Chart.js 2.X 中的条形值 - dataset.metadata 未定义 [英] Bar values in Chart.js 2.X - dataset.metadata undefined

查看:18
本文介绍了Chart.js 2.X 中的条形值 - dataset.metadata 未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Chart.js 2 的新手,因此我们将不胜感激.

I am quite new at Chart.js 2, so any help will be appreciated.

我正在尝试显示图表中每个条形的值.正如 使用图表在帕累托图中显示值中的建议.js 2.0.2 和其他用户我正在使用这个解决方案.但是,这部分会抛出异常 TypeError: dataset.metaData is undefined:

I'm trying to show values for each bar in the chart. As suggested in Display values in Pareto chart using Chart.js 2.0.2 and other users I'm using this solution. However, this part throws an exception TypeError: dataset.metaData is undefined :

dataset.metaData.forEach(function(p) {
   ctx.fillText(p._chart.config.data.datasets[p._datasetIndex].data[p._index], p._model.x, p._model.y  + 20);
});

我只想在栏上显示值.有什么帮助吗?

I just want to show the value over the bar. Any help?

推荐答案

使用下面更新的 onComplete,您的代码应该可以使用 Chart.js v2.1

With the below updated onComplete, your code should work with Chart.js v2.1

...
var options = {
    animation: {
        onComplete: function() {
            var ctx = this.chart.ctx;
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            var chart = this;
            var datasets = this.config.data.datasets;

            datasets.forEach(function (dataset, i) {
                ctx.font = "20px Arial";
                switch (dataset.type) {
                    case "line":
                        ctx.fillStyle = "Black";
                        chart.getDatasetMeta(i).data.forEach(function (p, j) {
                            ctx.fillText(datasets[i].data[j], p._model.x, p._model.y - 20);
                        });
                        break;
                    case "bar":
                        ctx.fillStyle = "White";
                        chart.getDatasetMeta(i).data.forEach(function (p, j) {
                            ctx.fillText(datasets[i].data[j], p._model.x, p._model.y + 20);
                        });
                        break;
                }
            });
        }
    },
    ...

<小时>

小提琴 - http://jsfiddle.net/0j4g7kxy/

我假设您只需要 bar,但我在 onComplete 中保留了 line 的代码,所以它应该可以工作也适用于线路.如果您也不需要,只需从 onComplete 代码中删除相关的 case 代码

I've assumed you needed only the bar, but I have retained the code for line in the onComplete, so it should work for lines too. If you don't need either, just remove the related case from the onComplete code

这篇关于Chart.js 2.X 中的条形值 - dataset.metadata 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆