javascript-如何在Chart.js中重新格式化工具提示?
作者:互联网
如何在Chart.js中重新格式化工具提示?该图表以x轴为时间,以y轴为销售额,并在工具提示中显示x和y的数据值.到目前为止,默认情况下工具提示可以使用,但是我想更改工具提示中的值.我可以通过在“时间”中重新定义tooltipFormat字段来重新格式化时间.但是对于y轴数据,我找不到类似的东西.例如,显示“ $1600”而不是“ Daily Ticket Sales:1600”.
example tooltip format image
谁能告诉我应该在哪里发生这种变化?
‘custom’回调函数可以在这里解决问题吗?这是代码,谢谢!
var dates=data.linechart.dates;
var times=[];
for (var i=0; i<dates.length; i++) {
times.push(moment(dates[i],'YYYY/MM/DD'));
}
// console.log(dates);
// console.log(times);
var salesData = {
labels: times,
datasets: [
{
label: "Daily Ticket Sales",
fill: false,
lineTension: 0,
backgroundColor: "#fff",
borderColor: "rgba(255,88,20,0.4)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(255,88,20,0.4)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(255,88,20,0.4)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 3,
pointHitRadius: 10,
data: data.linechart.sales,
}
]
};
var ctx = document.getElementById("daily_sale").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: salesData,
options: {
showLines: true,
responsive: true,
legend:{display:false},
tooltips:{
// backgroundColor:'rgba(0,255,0,0.8)',
custom: function(tooltip) {
// tooltip will be false if tooltip is not visible or should be hidden
if (!tooltip) {
return;
}
else{
console.log(tooltip);
}
}
},
scales:
{
xAxes: [{
type: "time",
time: {
displayFormat:'MM/DD/YY',
tooltipFormat: 'MM/DD/YY',
// unit: 'day',
}
}],
yAxes: [{
ticks:{ userCallback: function(value, index, values) {
// $sign and thousand seperators
return '$'+value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
},
},
}],
},
}
});
解决方法:
您可以在回调函数中自定义标签.
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return "Daily Ticket Sales: $" + tooltipItem.yLabel;
},
}
}
标签:chart-js,javascript 来源: https://codeday.me/bug/20191027/1941141.html