Skip to content

Tooltip

Tooltips offer an explorative way to inspect data points in your charts. They can be customized to display formatted values, handle missing data gracefully, and even include custom tooltip items.

A tooltip always displays a list of key-value pairs for the hovered data point(s). The keys are derived from the axis labels, and the values are formatted according to the axis formatting rules.

By default, tooltips are disabled for every chart type. You can enable them by setting the tooltip.isEnabled option to true.

const options = {
tooltip: {
isEnabled: true,
},
};

By default, the tooltip uses the same value formatting (tickFormat) as the axes.

To override those settings, use the extendedFormat option on the axes. Set a higher-precision format for the tooltip while keeping a simpler format for the axis ticks.

The same principles apply to the extendedUnit option. Set a different unit for the tooltip and override the tickUnit option.

const options = {
xAxis: {
dataKey: "date",
type: "time",
tickFormat: "%Y",
extendedFormat: "%d.%m.%Y",
},
yAxis: {
dataKey: "value",
type: "linear",
tickFormat: ".1f",
extendedFormat: ".2f",
},
};

When a data point has a missing value (undefined, null, or NaN), the tooltip will display “Keine Daten” by default. You can customize this label using the tooltip.undefinedLabel option.

const options = {
tooltip: {
undefinedLabel: "Keine Angabe",
},
};

If you want to display additional information like averages, sums, or other derived values in the tooltip, you can use a hook to add extra tooltip items.

Use the addHook("tooltip:items", ...) method on the chart instance to add a callback function. This function will be called whenever the tooltip is displayed, and it can return an array of additional key-value pairs to include in the tooltip. See Hooks for the exact shape of the callback argument and return value.

In the following example, an average value is calculated from the data points and added to the tooltip as an additional item.

import { LineChart } from "@statistikzh/charts";
const chart = LineChart({ el: document.getElementById("chart") });
chart.set({ data, options });
const unsubscribe = chart.addHook(
"tooltip:items",
({ xAxisValue, yAxisValue, groupValue, data }) => {
const avg =
data.reduce((sum, item) => sum + (item.value ?? 0), 0) / data.length;
return [{ key: "Durchschnitt", value: avg }];
},
);
// Later, if needed:
// unsubscribe();