[英]How to change NaN values to 0 in Chart.js?
我有一个图表,我在其中使用 AngularJS 获取值。
当没有值时,Angular 将其作为undefined
抛出。
当将这些值传递给图表时,图表不会显示它们(这很好,因为与 0 相同)。 但是在工具提示中,当悬停时,将值显示为“非数字”(NaN)。
如何让它将所有 NaN 值显示为0 (零)?
不知道看我的代码是否真的有帮助,但它是:
$scope.Chart = {
segmentShowStroke: false,
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
stacked: true,
ticks: {
autoSkip: false
},
gridLines: {
display: false
}
}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
},
gridLines: {
display: true,
color: "rgb(150,150,150)"
}
}]
},
legend: {
display: true,
position: 'top',
labels: {
usePointStyle: true,
fontColor: "white"
}
},
plugins: {
datalabels: {
color: '#171d28',
display: function(context) {
return context.dataset.data[context.dataIndex] !== 0;
},
anchor: 'center',
align: 'center',
clamp: true
},
deferred: {
yOffset: '45%',
delay: 200
}
}
};
$scope.Colors = [
{ backgroundColor: 'rgb(204,234,248)' },
{ backgroundColor: 'rgb(102,194,235)' },
{ backgroundColor: 'rgb(0,154,221)' },
{ backgroundColor: 'rgb(0,84,134)' }
];
$scope.Series = ['1 - Poor', '2 - Average', '3 - Acceptable', '4 - Good'];
$scope.Labels = ['Performance', 'Mobile Capability', 'Reporting'];
$scope.Data = [
[ ratingPerformance1, ratingMobileCapability1, ratingReporting1 ],
[ ratingPerformance2, ratingMobileCapability2, ratingReporting2 ],
[ ratingPerformance3, ratingMobileCapability3, ratingReporting3 ],
[ ratingPerformance4, ratingMobileCapability4, ratingReporting4 ]
];
Chart.js 提供了钩子供您自定义工具提示中的内容。 他们在其文档中提供了一个四舍五入示例,但您可以快速修改它以显示0
而不是NaN
。 它应该大致如下所示:
$scope.Chart = {
...
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += isNaN(tooltipItem.yLabel) ? '0' : tooltipItem.yLabel;
return label;
}
}
}
}
});
嘿,我和你有同样的错误,我试图在我的代码中加入很多条件,但在我得到最终结果后我失败了。 我成功了。
我的代码是这样的
helper[key].NoOfReels += isNaN((parseFloat(o.NoOfReels)) == "" || parseFloat(o.NoOfReels));
或者
isNaN(parseFloat(data[i].NoOfReels)) ? '0' : parseFloat(data[i].NoOfReels);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.