![](/img/trans.png)
[英]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.