Bar values in Chart.js 2.X - dataset.metadata undefined(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 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Chart.js 2.X 中的条形值 - dataset.metadata 未定义


基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 动态更新多个选择框 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01