[英]How display tooltip for each point of a line chart using Echarts (JS)
[英]Add a text as tooltip for each point on a line chart
我想知道ChartJS中是否有一个选项,如果我将鼠标悬停在折线图上的单个点上,如何查看更多信息。 目前,我的数据如下所示:
function drawChart(dataSets) {
Chart.defaults.global.maintainAspectRatio = false;
Chart.defaults.global.responsive = false;
var data = {
labels: ["ID"]
, datasets: dataSets
};
var options = {
title: {
display: true
, text: 'Custom Chart Title'
}
, scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
, xAxes: [{
type: "linear"
, position: "bottom"
}]
}
, tooltips: {
callbacks: {
label: function (tooltipItem, data) {
alert("Entered tooltip callback.");
return i18n.t('chart.count') + ': ' + getCount(tooltipItem, data.datasets);
}
}
}
};
var myChart = Chart.Line(ctx, {
data: data
, options: options
});
}
function getCount(tooltipItem, datasets) {
return datasets[tooltipItem.datasetIndex].data.find(datum => {
return datum.x === tooltipItem.xLabel && datum.y === tooltipItem.yLabel;
}).count;
}
这是一个数据点的样子:
x:5
, y:5
, count:2
但是alert
“ Entered tooltip”(输入的工具提示)从未被调用,我在做什么错? 相反,我在控制台(Google Chrome)上收到此错误:
看起来像这样:
label: sensorID,
data: [0,1,2,3],
backgroundColor: [
'rgba(' + rndColor() + ',' + rndColor() + ',' + rndColor() + ',0.2)'
],
borderColor: [
'rgba(' + rndColor() + ',' + rndColor() + ',' + rndColor() + ',0.2)'
],
options: {
tooltips: {
enabled: true
custom: function(tooltip) {
// code here to customize a tooltip
}
}
}
http://www.chartjs.org/docs/#chart-configuration-tooltip-configuration
http://www.chartjs.org/docs/#advanced-usage-external-tooltips
有关如何入门的示例,请参见sample / line-customTooltips.html。
我添加自定义工具提示的方式。 首先,我创建了一个数据集,在其中添加了诸如“计数”之类的附加信息。
x: 10,
y: 12,
count: 2
除非我在工具提示下的选项挂钩中手动获取此计数,否则它不会显示在图形中。
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return i18n.t('chart.count') +': ' + getCount(tooltipItem, data.datasets);
}
}
}
获取未在图表中表示的给定数据集的计数
function getCount(tooltipItem, datasets) {
return datasets[tooltipItem.datasetIndex].data.find(datum => {
return datum.x === tooltipItem.xLabel && datum.y === tooltipItem.yLabel;
}).count;
}
return [{
label: 'Example dataset',
backgroundColor: '#98cc99',
borderColor: '#98cc99',
pointHoverRadius: 3,
data: [ {x:1,y:2,count:3}, {x:2,y3,count:4}, ...]
}];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.