angular - 如何使用 Angular 中的 chart.js 条形图在标签之后和数值之前显示符号
问题描述
我在我的 Angular 项目中使用 chart.js v2 来呈现条形图并尝试在每个条形上以以下格式(所需输出)显示工具提示。示例: 其他:34.5 美元(不含 GST)。 我已经尝试了 labelBefor和LabelAfter 回调,但问题仍然存在。
代码:
loadChart() {
if (Array.isArray(this.monthData)) {
for (let i = 0; i < this.monthData.length; i++) {
this.CCA_DollarClr.push('#BD4FBD');
this.APT_DollarClr.push('#4F77BD');
this.CW_DollarClr.push('lightgrey');
this.SPRA_DollarClr.push('red');
this.OTHER_DollarClr.push('lightgreen');
}
}
if (this.BarChart) {
this.BarChart.destroy();
}
// Bar chart:
this.BarChart = new Chart('barChart', {
type: 'bar',
data: {
labels: this.monthData,
datasets: [{
label: 'CCA',
data: this.CCA_Dollar,
backgroundColor: this.CCA_DollarClr,
borderColor: ['#BD4FBD', '#BD4FBD', '#BD4FBD', '#BD4FBD', '#BD4FBD', '#BD4FBD'],
borderWidth: 1
},
{
label: 'APT',
data: this.APT_Dollar,
backgroundColor: this.APT_DollarClr,
borderColor: ['#4F77BD', '#4F77BD', '#4F77BD'],
borderWidth: 1
},
{
label: 'CW',
data: this.CW_Dollar,
backgroundColor: this.CW_DollarClr,
borderColor: ['lightgrey', 'lightgrey', 'lightgrey'],
borderWidth: 1
},
{
label: 'SPRA',
data: this.SPRA_Dollar,
backgroundColor: this.SPRA_DollarClr,
borderColor: ['#4F77BD', '#4F77BD', '#4F77BD'],
borderWidth: 1
},
{
label: 'OTHER',
data: this.OTHER_Dollar,
backgroundColor: this.OTHER_DollarClr,
borderColor: ['lightgrey', 'lightgrey', 'lightgrey'],
borderWidth: 1
}
],
},
options: {
title: {
// text: "Product Usage",
display: true
},
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
},
legend: {
onHover: function (e) {
e.target['style'].cursor = 'pointer';
}
},
hover: {
onHover: function (e) {
var point = this.getElementAtEvent(e);
if (point.length) e.target['style'].cursor = 'pointer';
else e.target['style'].cursor = 'default';
}
},
tooltips: {
// mode: 'index',
// callbacks: {
// afterLabel: function() {
// return ' $ (ex GST)';
// }
// }
}
}
});
}
有没有办法格式化工具提示,以便我可以在开头和结尾放置字符?如果我使用 beforLable 它输出为 $ (ext GST) Others: 3.45 这不是解决方案。任何指导都会非常有用
解决方案
您将需要使用正常的标签回调。
方法应该看起来像这样(在移动设备上所以无法测试它,所以从我的头顶上做这个):
callbacks: {
label: (ttItem, data) => {
return `${data.datasets[ttItem.datasetIndex].label}: £${ttItem.yLabel}`
}
}
推荐阅读
- python - SQLite3:如何使用 200 多个“FROM”子句进行“LEFT JOIN”?
- html - Visual Studio Code 文件夹命名约定
- r - 不使用 unique() 的重复数据帧
- javascript - VueX 用作帐户的缓存
- json - 响应代码导致解析 JSON Flutter 时出现问题
- postgresql - 从 docker 外部的客户端到 postgres 的连接对用户 postgres 具有致命的密码身份验证
- python - 逻辑回归sklearn中的coef_
- autosar - Autosar DEM_GetEventUdsStatus 与 DEM 事件的关联
- python - 使用 Python 中的定义创建一个定义以覆盖或更多 plt.plot()
- gmail - Gmail API:获取垃圾邮件横幅警告文本