Skip to content

With a line ​

A histogram and a line share the linear x axis, so a line point at x = 170 sits at 170 on the bin axis. Here a normal curve with the sample's mean and standard deviation, computed by hand, is drawn over a density histogram. A histogramDensity dataset draws such a curve, or a kernel density estimate, for you.

ts
// A line on the same linear axis: a normal curve over a density histogram.
import type {ChartConfiguration} from 'chart.js';
import {heights, mean, sd} from './data/index.js';

const m = mean(heights);
const s = sd(heights);
// A normal density with the sample's mean and standard deviation.
const curve = Array.from({length: 81}, (_, i) => {
  const x = 140 + i * 0.75;
  const y = Math.exp(-(((x - m) / s) ** 2) / 2) / (s * Math.sqrt(2 * Math.PI));
  return {x, y};
});

const config: ChartConfiguration<'histogram' | 'line'> = {
  type: 'histogram',
  data: {
    datasets: [
      {
        type: 'line',
        label: 'Normal curve',
        data: curve,
        borderColor: 'rgb(255, 99, 132)',
        borderWidth: 2,
        pointRadius: 0
      },
      {
        label: 'Adults',
        data: heights,
        binWidth: 4,
        binStart: 140,
        stat: 'density',
        backgroundColor: 'rgba(54, 162, 235, 0.5)'
      }
    ]
  },
  options: {
    scales: {
      x: {title: {display: true, text: 'Height (cm)'}},
      y: {title: {display: true, text: 'Density'}}
    }
  }
};

export default config;

Released under the MIT License.