如何编辑 ChartJS 工具提示以在工具提示中添加自定义字符串
例如:我想更改工具提示,例如“January:28 Files”或只是“28 Files”
重新定义默认的全局工具提示模板,如下:
Chart.defaults.global.tooltipTemplate =
"<%if (label){%><%=label%>: <%}%><%= value %>";
这是另一个例子:
var ctx = document.getElementById("canvas").getContext("2d");
var myBarChart = new Chart(ctx).Bar(data, {
tooltipTemplate: "<%= value %> Files"
});
之前的精彩答案不适用于 ChartJS 3。此示例来自 官方文档:
const chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
plugins: {
tooltip: {
callbacks: {
label: function(context) {
var label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(context.parsed.y);
}
return label;
}
}
}
}
}
);
根据我发现对我有帮助的其他回复,显然标签属性可以设置为函数,例如,格式化货币:
var overrides = {
// show lables as currency
scaleLabel: toCurrency,
// String - Template string for single tooltips
tooltipTemplate: toCurrency,
// String - Template string for multiple tooltips
multiTooltipTemplate: toCurrency
}
function toCurrency(label) {
return '$' + label.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}