Aller au contenu

Courbes et trous ​

Trois façons de relier les points d'une série : segments droits, courbe lisse monotone et step (escalier). Une valeur manquante (NaN) coupe la ligne avec gaps: 'break', ou est sautée par défaut.

ts
import * as d3 from 'd3'
import {
  d3pAutoInteractionArea, D3PAxis, D3PAxisDomain, D3PChart, D3PCursorIndicator, d3pDomLegend, d3pDomTooltip,
  D3PLegendBundle, D3PLineRenderer, D3PSeries, D3PTooltip, getGlobalBus,
} from 'd3pict'
// your series data: replace these generators with your own values
import { walk } from './data'

const bus = getGlobalBus()

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

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
const COLORS = d3.schemeTableau10
const month = (v: unknown) => MONTHS[Math.round(Number(v))] ?? ''
/** A series of numbers over 12 months, x being the month index. */
const monthly = (seed: number, base: number, spread: number) => walk(seed, 12, base, spread, 5, 100).map((v, i) => [i, v] as [number, number])

const raw = walk(5, 30, 50, 25, 10, 90)
const dx = new D3PAxisDomain({ bus, domain: [0, 29] })
const dy = new D3PAxisDomain({ bus, domain: [0, 100] })
const x = new D3PAxis({ bus, name: 'x', domain: dx })
const y = new D3PAxis({ bus, name: 'y', domain: dy, position: 'left', props: { grid: { enabled: true } } })

// one series with a hole in it, joined three ways
const withGap = new D3PSeries({ bus, name: 'linear', data: raw.map((v, i) => (i === 12 || i === 13 ? NaN : v)) })
const above = new D3PSeries({ bus, name: 'monotone', data: raw.map((v) => Math.min(100, v + 15)) })
const below = new D3PSeries({ bus, name: 'step', data: raw.map((v) => Math.max(0, v - 25)) })
const linear = new D3PLineRenderer({ bus, series: withGap, props: { style: { color: COLORS[0], curve: 'linear', gaps: 'break' } } })
const monotone = new D3PLineRenderer({ bus, series: above, props: { style: { color: COLORS[1], curve: 'monotone' } } })
const step = new D3PLineRenderer({ bus, series: below, props: { style: { color: COLORS[2], curve: 'step' } } })

const cursor = new D3PCursorIndicator({ bus })
const tooltip = new D3PTooltip({ bus })
const legend = new D3PLegendBundle({ bus })
const objects = [x, y, linear, monotone, step, cursor, tooltip, legend]

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)
const stopLegend = d3pDomLegend(legend)

Tous les types de graphiques · comment chaque type est construit