Reputation: 3529
In a react-chartjs-2 bar chart: How do I customize all the information shown inside the tooltip when hovering over a bar?
I would expect something like data.datasets[x].tooltip.callback
to be available, but I can't find anything useful/working.
Note: I prefer a more generalized answer over a very specific answer to the concrete situation I'm describing below. This would probably be more useful for other readers.
I'm plotting data in a bar graph.
X values are given as timestamps (milliseconds). Y values are numbers representing a percentage. Example:
data = [
{ x: timestamp(2022, 1, 1, 1, 15), y: 1 },
{ x: timestamp(2022, 1, 1, 1, 30), y: 2 },
// ...
]
1:15
, 1:30
, ...0 %
, 0.5 %
, 1%
, ....When I hover over a bar, it will show:
I want the tooltip to show:
1:15
).2%
).
function timestamp(year: number, month: number, day: number, hour: number, minute: number) {
const timestamp = new Date(year, month - 1, day, hour, minute).valueOf();
return timestamp;
}
export const TimeGraph: React.FC = () => {
const data = [
{ x: timestamp(2022, 1, 1, 1, 15), y: 1 },
{ x: timestamp(2022, 1, 1, 1, 30), y: 2 },
{ x: timestamp(2022, 1, 1, 1, 45), y: 3 },
{ x: timestamp(2022, 1, 1, 2, 0), y: 4 },
{ x: timestamp(2022, 1, 1, 2, 15), y: 2 },
];
const xValues = data.map((value: any) => {
return value.x;
});
const yValues = data.map((value: any) => {
return value.y;
});
const options = {
scales: {
x: {
grid: {
display: false,
},
ticks: {
callback: (index: any) => {
const date = new Date(xValues[index]);
return date.getHours() + ':' + date.getMinutes();
},
},
},
yAxes: {
grid: {
display: false,
},
ticks: {
callback: (value: any) => {
return value + ' %';
},
},
},
},
plugins: {
legend: {
position: 'top' as const,
},
title: {
display: false,
},
},
};
const chartData = {
labels: xValues,
datasets: [
{
label: 'TODO: remove',
data: yValues,
},
],
};
return (
<>
<Bar options={options} data={chartData} height={150} />
</>
);
};
Upvotes: 3
Views: 12942
Reputation: 3529
You can customize the tooltip via options.plugins.tooltip.callbacks
(Reference)
const options = {
plugins: {
tooltip: {
callbacks: {
title: (xDatapoint) => {return formatXValue(xDatapoint.raw)},
label: (yDatapoint) => {return formatYValue(yDatapoint.raw)},
}
}
},
}
Note:
This was not part of the question, but it showed up in the screenshot:
options.plugins.legend.display: false
disables the legend.
Upvotes: 4