Skip to content

Mean and median lines ​

Mark the mean and the median with vertical lines. A small inline plugin draws them after the bars, at the pixel the x scale gives for each value. Because the bin axis is linear, scales.x.getPixelForValue(value) is exactly where that value lies among the bins.

ts
// Mean and median as vertical lines, drawn by a small inline plugin.
import type {Chart, ChartConfiguration, Plugin} from 'chart.js';
import {mean, median, responseTimes} from './data/index.js';

const markers = [
  {label: 'Mean', value: mean(responseTimes), color: 'rgb(255, 99, 132)'},
  {label: 'Median', value: median(responseTimes), color: 'rgb(75, 192, 192)'}
];

const meanAndMedian: Plugin<'histogram'> = {
  id: 'meanAndMedian',
  afterDatasetsDraw(chart: Chart<'histogram'>) {
    const {ctx, chartArea, scales} = chart;
    ctx.save();
    for (const marker of markers) {
      const x = scales.x.getPixelForValue(marker.value);
      ctx.strokeStyle = marker.color;
      ctx.lineWidth = 2;
      ctx.setLineDash([6, 4]);
      ctx.beginPath();
      ctx.moveTo(x, chartArea.top);
      ctx.lineTo(x, chartArea.bottom);
      ctx.stroke();
      ctx.fillStyle = marker.color;
      ctx.fillText(`${marker.label}: ${marker.value.toFixed(0)} ms`, x + 6, chartArea.top + 12);
    }
    ctx.restore();
  }
};

const config: ChartConfiguration<'histogram'> = {
  type: 'histogram',
  data: {
    datasets: [{label: 'Requests', data: responseTimes, binWidth: 20, domain: [0, 600]}]
  },
  options: {
    scales: {
      x: {title: {display: true, text: 'Response time (ms)'}},
      y: {title: {display: true, text: 'Requests'}}
    }
  },
  plugins: [meanAndMedian]
};

export default config;

chartjs-plugin-annotation works too: a line annotation with scaleID: 'x' and value: mean lands at the same place.

Released under the MIT License.