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.
Concrete Situation
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 },
// ...
]
- X-axis ticks are formatted as
1:15
,1:30
, ... - Y-axis ticks are formatted as
0 %
,0.5 %
,1%
, ....
Problem
When I hover over a bar, it will show:
- The timestamp in milliseconds
- The label of the data
I want the tooltip to show:
- The formatted version of the timestamp (like
1:15
). - The formatted version of the y-value (like
2%
). - No label at all
Complete Code of React Component
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} />
</>
);
};