我有一个条形图,单击任何条形图时,数据都会显示在工具提示中。我需要 onClick
函数中的工具提示数据。
以下是我的条形图代码:
var tool = new Chart(canvas, {
type: 'bar',
data: data,
options: {
legend: {
display: true,
labels: {
fontColor: 'rgb(255, 99, 132)'
},
position : 'bottom'
},
title: {
display: true,
text: title
},
scales: {
xAxes: [{stacked: true,barPercentage: 5.0,
categoryPercentage: 0.2}],
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true
},
barPercentage: 0.3
}]
},
events: [ "click"],
onClick: function(event, array){
console.log("tool.data:",tool.tooltip);
}
}
});
我想要点击函数中的数据,例如“missed”、“medium”、78。
最佳答案
您可以使用以下onClick
函数来获取工具提示的数据:
onClick: function(event, element) {
var activeElement = element[0];
var data = activeElement._chart.data;
var barIndex = activeElement._index;
var datasetIndex = activeElement._datasetIndex;
var datasetLabel = data.datasets[datasetIndex].label;
var xLabel = data.labels[barIndex];
var yLabel = data.datasets[datasetIndex].data[barIndex];
console.log(datasetLabel, xLabel, yLabel);
}
此外,您还需要将图表的悬停
模式设置为最近
才能使其正常工作:
hover: {
mode: 'nearest'
}
查看working example .
关于javascript - 如何获取点击的条形图工具提示数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47075025/