I am using chart.js in React.
I have read and implemented: Chart.js - show tooltip when hovering on legend
Unfortunately, this is not providing the desired results. I believe this is because this is being implemented in javascript, and I am implementing react. Not sure if that is impacting anything.
const data = {
labels: ['One', 'Two', 'Three'],
datasets: [{
data: [4, 5, 3],
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
borderWidth: 1,
hoverBorderWidth: 3
}]
};
const options = {
plugins: {
legend: {
onHover: (evt: any, legendItem: any, legend: any) => {
const index = legend.chart.data.labels.indexOf(legendItem.text);
const activeSegment = legend.chart.getDatasetMeta(0).data[index];
// console.log(activeSegment);
// activeSegment.options.backgroundColor = activeSegment._options.hoverBackgroundColor;
// activeSegment.options.borderWidth = activeSegment._options.hoverBorderWidth;
legend.chart.tooltip._active = [activeSegment];
legend.chart.update();
legend.chart.draw();
},
onLeave: (evt: any, legendItem: any, legend: any) => {
const index = legend.chart.data.labels.indexOf(legendItem.text);
// const activeSegment = legend.chart.getDatasetMeta(0).data[index];
// activeSegment.options.backgroundColor = activeSegment._options.backgroundColor;
// activeSegment.options.borderWidth = activeSegment._options.borderWidth;
legend.chart.tooltip._active = [];
legend.chart.update();
legend.chart.draw();
}
},
},
}
with the end of this component returning the following:
return <Doughnut data={data} options={options} />;
This produces the chart that is shown in the stackoverflow post that I linked.
For v3 you can use an method to set the tooltip programatically
onHover: (evt, item, legend) => {
const chart = legend.chart;
const tooltip = chart.tooltip;
const chartArea = chart.chartArea;
tooltip.setActiveElements([{
datasetIndex: 0,
index: item.index,
}], {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
chart.update();
},