Skip to content

Histogram ​

D3PHistogram bins the values of a series; its series has the edges of each bin (x0, x1), which the bars use as widths. An annotation marks the mean.

ts
import * as d3 from 'd3'
import {
  D3PAnnotationLine, D3PAutoDomain, d3pAutoInteractionArea, D3PAxis, D3PAxisDomain, D3PBarRenderer, D3PChart,
  d3pDomTooltip, D3PHistogram, D3PSeries, D3PTooltip, getGlobalBus,
} from 'd3pict'
// your series data: replace these generators with your own values
import { rng } from './data'

const bus = getGlobalBus()

const container = document.getElementById('app')! // any element with a size: the chart fills it

const random = rng(21)
const gaussian = () => (random() + random() + random() + random() - 2) * 15 + 50
const samples = new D3PSeries({ bus, name: 'samples', data: Array.from({ length: 400 }, gaussian) })
// the histogram bins the values; its series has the edges of each bin, which the bars use as widths
const histogram = new D3PHistogram({ bus, series: samples, thresholds: 16, name: 'count' })

const dx = new D3PAxisDomain({ bus, domain: [0, 1] })
const dy = new D3PAxisDomain({ bus, domain: [0, 1] })
const auto = new D3PAutoDomain({ bus })
auto.linkSeries(histogram.series, [dx, dy])

const x = new D3PAxis({ bus, name: 'x', domain: dx })
const y = new D3PAxis({ bus, name: 'y', domain: dy, position: 'left', props: { grid: { enabled: true } } })
const bars = new D3PBarRenderer({ bus, series: histogram.series, props: { style: { color: '#59a14f' } } })
const mean = new D3PAnnotationLine({ bus, axis: x, value: d3.mean(samples.data, (p) => p[1])!, label: 'mean', style: { stroke: '#e15759', strokeDasharray: '4,3' } })

const tooltip = new D3PTooltip({ bus })
const objects = [x, y, bars, mean, tooltip]

const chart = new D3PChart({ container, bus })
const stopArea = d3pAutoInteractionArea(chart) // before the objects: the cursor, the tooltip and the tools ask for an interaction area
objects.forEach((o) => o.addToChart(chart))
const stopTooltip = d3pDomTooltip(tooltip)

All the chart types · how each type is built