Skip to content

Tooltips and interaction ​

Hover anywhere along a bin, at any height: the histogram's 'bin' interaction mode selects the bin under the pointer. The tooltip shows the bin's range and its value. Tooltip callbacks receive the bin as item.parsed.

ts
// Tooltip text from the bin: its edges and its count.
import type {ChartConfiguration} from 'chart.js';
import {heights} from './data/index.js';

const config: ChartConfiguration<'histogram'> = {
  type: 'histogram',
  data: {
    datasets: [{label: 'Adults', data: heights, binWidth: 5, binStart: 140}]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          // `parsed` is the bin: x0 and x1 are its edges, count its number of values.
          title: (items) => {
            const {x0, x1} = items[0].parsed;
            return `From ${String(x0)} cm to under ${String(x1)} cm`;
          },
          label: (item) => `${String(item.parsed.count)} adults`
        }
      }
    },
    scales: {
      x: {title: {display: true, text: 'Height (cm)'}},
      y: {title: {display: true, text: 'Count'}}
    }
  }
};

export default config;

When the bins change ​

onBinsComputed is called with the bins each time the dataset is binned: when the chart is created, and on every update. Use it to show the bins elsewhere on the page, or to log them. getBins reads the same result at any time.

ts
// onBinsComputed reports the bins after each binning; here the subtitle shows them.
import type {ChartConfiguration} from 'chart.js';
import type {BinsComputedEvent} from 'chartjs-chart-histogram';
import {waitingTimes} from './data/index.js';

let summary = '';

const config: ChartConfiguration<'histogram'> = {
  type: 'histogram',
  data: {
    datasets: [
      {
        label: 'Eruptions',
        data: waitingTimes,
        bins: 'fd',
        // Called on every update that bins the data, before the chart is drawn.
        onBinsComputed({counts, width, rule, dropped}: BinsComputedEvent) {
          const total = counts.reduce((sum, count) => sum + count, 0);
          summary = `${String(counts.length)} bins of ${width?.toFixed(2) ?? 'mixed'} min (rule ${rule}), ${String(total)} values, ${String(dropped)} left out`;
        }
      }
    ]
  },
  options: {
    plugins: {
      // A function, read when the subtitle is laid out, after the bins are computed.
      // Chart.js resolves it like any scriptable option, though its types expect a string.
      subtitle: {display: true, text: (() => summary) as unknown as string}
    },
    scales: {
      x: {title: {display: true, text: 'Minutes between eruptions'}},
      y: {title: {display: true, text: 'Eruptions'}}
    }
  }
};

export default config;

Released under the MIT License.