我有一个包含许多数据集的条形图。我只想向其中一个添加自定义工具提示,并提供一些特定的属性。特别是,这是我的图表:
var grafoprocessi = new Chart(ctx2, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: ['Processi', 'Startup', 'OpenCoesione'],
datasets: [{
label: '2010',
backgroundColor: 'rgb(255, 230, 230)',
borderColor: 'rgb(255, 230, 230)',
data: array2010
},
{label:'2011',
backgroundColor: 'rgb(255, 204, 204)',
borderColor: 'rgb(255, 204, 204)',
data: array2011
},
{label:'2012',
backgroundColor: 'rgb(255, 179, 179)',
borderColor: 'rgb(255, 179, 179)',
data: array2012
},
{label:'2013',
backgroundColor: 'rgb(255, 102, 102)',
borderColor: 'rgb(255, 102, 102)',
data: array2013
},
{label:'2014',
backgroundColor: 'rgb(255, 26, 26)',
borderColor: 'rgb(255, 26, 26)',
data: array2014
},
{label:'2015',
backgroundColor: 'rgb(204, 0, 0)',
borderColor: 'rgb(204, 0, 0)',
data: array2015
},
{label:'2016',
backgroundColor: 'rgb(153, 0, 0)',
borderColor: 'rgb(153, 0, 0)',
data: array2016
},
{label:'2017',
backgroundColor: 'rgb(153, 0, 51)',
borderColor: 'rgb(153, 0, 51)',
data: array2017
},
{label:'2018',
backgroundColor: 'rgb(230, 0, 76)',
borderColor: 'rgb(230, 0, 76)',
data: array2018
},
{label:'2019',
backgroundColor: 'rgb(255, 26, 102)',
borderColor: 'rgb(255, 26, 102)',
data: array2019
},
{label:'2020',
backgroundColor: 'rgb(255, 128, 170)',
borderColor: 'rgb(255, 128, 170)',
data: array2020
}]
},
// Configuration options go here
options: {}
});
我想向一个标签“ OpenCoesione”添加一个自定义工具提示,其中包含数组中的数据。我不知道是否有解决方案,因为我已经看到所有更改所有工具提示。我希望所有工具提示在“ OpenCoesione”栏旁边保持不变。
答案 0 :(得分:1)
有点棘手的解决方案,但似乎可行。 StackBlitz demo。
寻找其他类似问题的答案(例如How to diable a tooltip for a specific dataset),我找不到动态禁用工具提示并使用自定义工具提示的方法。
主要思想是使默认工具提示保持启用状态,但在custom
工具提示功能中将其更改为禁用状态。
options: {
responsive: true,
tooltips: {
enabled: true,
custom: function (tooltipModel) {
if (isCustomTooltipMode(tooltipModel, 'OpenCoesione')) {
setDefaultTooltipEnabled(this, false);
} else {
setDefaultTooltipEnabled(this, true);
return;
}
var tooltipEl = document.getElementById('chartjs-tooltip');
// Hide if no tooltip
if (tooltipModel.opacity === 0 && tooltipEl) {
tooltipEl.style.opacity = 0;
return;
}
// Create element on first render
createCustomTooltip(this, tooltipEl, tooltipModel);
}
}
}
function isCustomTooltipMode(tooltipModel, labelName) {
return tooltipModel.dataPoints == null || tooltipModel.dataPoints[0].xLabel === labelName;
}
/*
the hacky way (could not find the better one)
*/
function setDefaultTooltipEnabled(chart, enabled) {
chart._chart.tooltip._options.enabled = enabled;
}
在createCustomTooltip
函数中,您可以定义“ OpenCoesione”工具提示的外观。
Chart.js文档: External custom tooltips,Tooltip Model,Tooltip Item