Code

D3.js

Histogram

Intermediate 500 random samples from a normal distribution binned by d3.bin(), with a red normal-curve overlay derived from the sample mean and standard deviation. d3-array/bin

// Generate data
const rng = d3.randomNormal(50, 12);
const data = Array.from({ length: 500 },
  () => Math.max(0, Math.min(100, rng())));

// Create bin generator
const binner = d3.bin()
  .domain([0, 100])
  .thresholds(x.ticks(20));   // ~20 bins

const bins = binner(data);

// Y-scale from 0 to the tallest bin
const y = d3.scaleLinear()
  .domain([0, d3.max(bins, b => b.length)])
  .range([height, 0]);

// Draw bars
svg.selectAll('rect')
  .data(bins).join('rect')
  .attr('x', d => x(d.x0) + 1)
  .attr('y', d => y(d.length))
  .attr('width',
    d => x(d.x1) - x(d.x0) - 2)
  .attr('height',
    d => height - y(d.length));

// Normal-curve overlay
const mean = d3.mean(data);
const sd   = d3.deviation(data);
Key APIs
  • d3.bin() — partitions continuous data into discrete bins
  • .domain([min,max]) — sets the observable extent
  • .thresholds(array|count) — number of thresholds or explicit breakpoints
  • bin.x0 / bin.x1 — lower and upper bound of each bin
  • d3.mean() / d3.deviation() — summary statistics
  • d3.randomNormal(μ,σ) — samples from a normal distribution