Skip to content

Box plot ​

d3pBoxPlotRows(groups) computes quartiles, whiskers and outliers from raw samples; D3PBoxPlotRenderer draws them.

ts
import {
  D3P_BOXPLOT_COLUMNS, D3PAutoDomain, d3pAutoInteractionArea, D3PAxis, D3PAxisDomain, D3PBoxPlotRenderer,
  d3pBoxPlotRows, D3PChart, d3pDomTooltip, 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(33)
const sample = (mean: number, spread: number) => Array.from({ length: 40 }, () => mean + (random() + random() + random() - 1.5) * spread + (random() > 0.97 ? spread * 3 : 0))
const groups: [string, number[]][] = [['Control', sample(50, 20)], ['Dose A', sample(58, 18)], ['Dose B', sample(66, 25)], ['Dose C', sample(48, 12)]]
// quartiles, whiskers and outliers computed from the raw samples
const response = new D3PSeries({ bus, name: 'response', columns: [...D3P_BOXPLOT_COLUMNS], primary: 'median', data: d3pBoxPlotRows(groups) })

const dx = new D3PAxisDomain({ bus, domain: groups.map((g) => g[0]) })
const dy = new D3PAxisDomain({ bus, domain: [0, 1] })
const auto = new D3PAutoDomain({ bus })
auto.linkSeries(response, [dx, dy])

const x = new D3PAxis({ bus, name: 'x', domain: dx, scaleType: 'band' })
const y = new D3PAxis({ bus, name: 'y', domain: dy, position: 'left', props: { grid: { enabled: true } } })
const boxes = new D3PBoxPlotRenderer({ bus, series: response, props: { style: { color: '#4e79a7' } } })

const tooltip = new D3PTooltip({ bus })
const objects = [x, y, boxes, 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