Skip to content

API Graphique en courbes

Tout ce qu'il faut pour intégrer un graphique en courbes dans votre code ; pour la présentation et les démos, consultez la démo Graphique en courbes.

Import

ts
import "@michi-vz/wc/line-chart";
// <michi-vz-line-chart> is now defined
ts
import { mountLineChart } from "@michi-vz/core";

const chart = mountLineChart(el, props);

Propriétés

PropTypeDefaultDescription
timelineboolean | TimelinePeriodConfig-Opt-in "play through years" (cumulative): the marks draw UP TO the active period and extend as the timeline steps; `interpolate` sweeps smoothly between years, `false` jump-cuts. Headless controller via `chart.timeline()` plus the built-in play button + scrubber. Off by default; wins over `progressiveDraw` when both are set.
dataSet*LineDataItem[]-Array of line series, each with its own points
titlestring-Optional chart title rendered above the plot
yAxisDomain[number, number]-Fix the y-axis range as [min, max] instead of deriving it from the data
yAxisScale"linear" | "log""linear"Y-axis scale: "linear" (default) or a base-10 "log" scale. In "log" mode, a non-positive value (<= 0) can't be plotted, so those points are dropped as missing (reported via `onDataWarning`); a dataSet with no positive values at all renders the no-data state instead.
xAxisDataType"date_annual" | "date_monthly" | "number""number"How x values are parsed and formatted: yearly dates, monthly dates, or plain numbers
xAxisFormat(d: number | string) => string-Formats an x tick value into its display label
yAxisFormat(d: number | string) => string-Formats a y tick value into its display label
ticksnumber5Approximate number of x-axis ticks to generate
yTicksnumber-Number of y-axis ticks (default 10, matching the legacy denser value axis).
showGridLinesboolean-Draw horizontal dashed grid lines at each y tick (default true).
showVerticalGridLinesboolean-Draw vertical dashed grid lines at each x tick (default false - the legacy chart drew none).
highlightZeroLineboolean-Emphasise the y=0 grid line with a darker solid stroke (default true).
tickValuesArray<number | Date>-Explicit tick values, overriding the generated ones
fillPeriodTicksboolean-Draw a tick for EVERY period across the axis range (every month/year), not just the periods present in the data. Periods with no value render faded and show `noDataTickTooltip` on hover. Opt-in; default false.
noDataTickTooltip(date: number) => string-Tooltip content (plain text or sanitized HTML) for a faded no-data tick; receives the tick's epoch-ms value. Used only with `fillPeriodTicks`. Default: a localized "Data not available".
noDataTickColorstring-Colour for faded no-data tick labels; sets the `--michi-vz-tick-nodata` CSS var on the host. Used only with `fillPeriodTicks`.
curve"curveBumpX" | "curveLinear" | "curveMonotoneX"-Default interpolation for every series (per-series `curve` wins).
detectGapsbooleanfalseAuto-derive `certainty` from missing periods (dashes the gap segment).
expectedStepnumber-Expected cadence in axis units; REQUIRED for xAxisDataType "number".
showDataPointsbooleanfalseWhether to draw a marker at each data point (default false)
enableMouseLineboolean | MouseLineConfigtrueSolid vertical crosshair line snapped to the nearest data point x on hover; pass a config object to style it (default true)
singlePointLineboolean | SinglePointLineConfig-true / config draws a horizontal guide line for single-point series.
fontFamilystring-Font family for axis/title/tooltip text (SVG + canvas). Sets the --michi-vz-font-family CSS var so both renderers resolve it.
filterFilter-Top-N / sort filter applied to the data before rendering
progressiveDrawboolean | ProgressiveDrawConfig-Animate each line drawing itself left to right on mount (progressive reveal). `true` uses defaults; pass a config to tune duration, easing, tip labels, and autoplay. Off by default, so existing charts are unchanged. Respects prefers-reduced-motion: the chart then renders fully drawn instantly. Ignored by the webgpu renderer.
isLoadingboolean-Show the loading overlay and skip the no-data check (legacy michi-vz parity).
isNodata| boolean | ((dataSet: LineDataItem[] | null | undefined) => boolean)-No-data override: boolean, or a predicate on dataSet; default = empty/all-empty-series.
noDataLabelstring-Text for the vanilla default no-data overlay (ignored when suppressed).
suppressDefaultOverlayboolean-A framework wrapper sets this to render its OWN loading/no-data node instead.
tooltipFormatter( d: DataPoint, series: DataPoint[], dataSet: LineDataItem[], ) => string-Returns custom tooltip HTML for a hovered datum (sanitized before it is inserted)
sharedTooltipbooleanfalseWhen true, hovering anywhere in the plot shows ONE tooltip listing every series' value at the nearest x (year) - the "shared"/crosshair tooltip - instead of the single nearest series. Pairs with the crosshair (enableMouseLine, on by default).
sharedTooltipFormatter(input: { x: number | string; xLabel: string; entries: Array<{ label: string; value: number; color: string; d: DataPoint }>; }) => string-Custom HTML for the shared tooltip. `entries` is one row per series that has a point at the hovered x, in dataSet order, each with its resolved colour.
onHighlightItem(labels: string[]) => void-Called when the hovered/highlighted label(s) change
svgChildrenstring-Pre-serialised SVG markup injected as direct <svg> children (axis-title text, reference lines). The React wrapper fills this from `children`; mirrors the legacy <LineChart>'s `{children}` slot.
Common props - shared by every chart (14)
PropTypeDefaultDescription
widthnumber1000Chart width in pixels
heightnumber500Chart height in pixels
marginMargin{ top: 50, right: 50, bottom: 50, left: 60 }Inner margins (top/right/bottom/left, in px) reserved for axes, titles, and labels
colorsstring[]-Categorical palette for series/labels without an explicit colour or colorsMapping entry
colorsMappingRecord<string, string>-Explicit label -> colour map; takes precedence over the palette and per-item colours
highlightItemsstring[]-Labels to emphasise; all other marks dim
disabledItemsstring[]-Labels to hide and exclude from scales/stacks
renderer"svg" | "canvas" | "webgpu""svg"Render as inline SVG (default) or to a canvas (faster for large datasets); getContext() is identical either way
localestring-BCP-47 locale used for number and date formatting
skipColorMappingDispatchbooleanfalseExternal-CSS mode: unmapped labels resolve to transparent and onColorMappingGenerated is not emitted, so mark colours come from your CSS via the data-label-safe contract
enableTransitionsbooleantrueAnimate updates with CSS transitions (default true)
onColorMappingGenerated(mapping: Record<string, string>) => void-Called with the resolved label -> colour map after the chart assigns colours
onChartDataProcessed(context: ChartContext) => void-Called with the renderer-agnostic ChartContext whenever the data is (re)processed
onDataWarning(warnings: DataWarning[]) => void-Called with any non-fatal data warnings (duplicate labels, non-finite values, non-monotonic dates, ...)

Affichage de la grille et des axes

Quatre propriétés contrôlent la densité des graduations de l'axe des ordonnées et l'affichage des lignes de grille :

PropriétéValeur par défautRemarques
yTicks10Nombre approximatif de graduations sur l'axe des ordonnées. La valeur par défaut historique était 10 ; réduisez-la (par exemple 5) pour un axe moins dense.
showGridLinestrueLignes de grille horizontales en pointillés à chaque graduation de l'axe des ordonnées.
showVerticalGridLinesfalseLignes de grille verticales en pointillés à chaque graduation de l'axe des abscisses. Le graphique historique n'en affichait aucune ; à activer uniquement lorsque ces repères supplémentaires améliorent la lisibilité.
highlightZeroLinetrueTrace la ligne y=0 sous forme de trait plein (coloré via --michi-vz-zero-line, avec repli sur la couleur de la grille) plutôt qu'une graduation en pointillés classique. Utile lorsqu'un jeu de données couvre des valeurs positives et négatives.

État de chargement et d'absence de données

Le moteur gère un attribut data-mv-state sur l'élément hôte, avec trois valeurs possibles - "loading", "nodata" et "ready" - et affiche des overlays intégrés pour les deux premières, sauf désactivation explicite.

PropriétéTypeValeur par défautRemarques
isLoadingbooleanfalseAffiche l'overlay .mv-loading et ignore entièrement la vérification d'absence de données.
isNodataboolean | (dataSet) => boolean-Remplace le prédicat par défaut (dataSet vide ou chaque série ayant zéro point). Passez false pour forcer le rendu du graphique même quand les données semblent vides.
noDataLabelstring-Texte affiché dans l'overlay .mv-nodata par défaut. Ignoré lorsque suppressDefaultOverlay vaut true.
suppressDefaultOverlaybooleanfalseEmpêche le moteur d'injecter son propre nœud de chargement / d'absence de données. À utiliser lorsqu'un wrapper de framework (par exemple le LineChart de @michi-vz/react) affiche à la place isLoadingComponent / isNodataComponent sous forme d'overlay React. L'hôte n'est jamais démonté - l'overlay est simplement superposé.

Comportement du wrapper React

Le LineChart de @michi-vz/react définit automatiquement suppressDefaultOverlay et affiche isLoadingComponent / isNodataComponent sous forme de nœud React positionné au-dessus de l'hôte du graphique. Le DOM du graphique est toujours monté, donc isNodataComponent se déclenche même sur des données vides, sans prédicat personnalisé.

Police de caractères

fontFamily définit la propriété CSS personnalisée --michi-vz-font-family sur l'élément hôte, lue à la fois par le moteur de rendu de texte SVG et par la sonde getComputedStyle du canvas. La police doit déjà être chargée par la page - aucun embarquement de police n'est effectué.

ChartContext / legendData

onChartDataProcessed reçoit un LineChartContext qui étend BaseChartContext. La base porte désormais un champ legendData :

ts
interface LegendItem {
  label: string;         // series label as it appears in dataSet
  color: string;         // resolved colour at the time of processing
  order: number;         // appearance order (legend slot index)
  disabled?: boolean;    // true when the label is currently hidden
  dataLabelSafe?: string; // sanitizeForClassName(label) - the CSS hook the canvas colour probe matches
}

interface BaseChartContext {
  // ... existing fields ...
  legendData?: LegendItem[]; // populated by LineChart; treat absence as []
}

legendData est la charge utile canonique pour les autorités de couleur côté consommateur. Un wrapper de framework qui pilote son propre CSS de couleur (par exemple useChartUtils de thd MonitorV2) lit legendData[].{label, dataLabelSafe, color, disabled} à chaque appel de onChartDataProcessed et émet des règles stroke/fill par étiquette ciblant l'attribut data-label-safe. Cela évite d'avoir à recouper colorsMapping avec l'ordre des séries.

Événements

Le composant web émet ces CustomEvents à bouillonnement (bubbling) (le moteur expose les mêmes via les callbacks on* du tableau ci-dessus) :

ÉvénementDétailSe déclenche quand
michi-vz:highlightstring[]la surbrillance au survol change
michi-vz:colormappingRecord<string, string>un mapping de couleurs est généré
michi-vz:dataprocessedChartContextles données sont (re)traitées
michi-vz:datawarningDataWarning[]des avertissements sur les données d'entrée sont détectés

getContext()

mountLineChart(el, props).getContext() retourne un LineChartContext indépendant du moteur de rendu (statistiques structurées + un résumé déterministe en langage naturel + une table d'accessibilité). Voir Contexte LLM.

Source

Les propriétés sont typées comme LineChartProps dans @michi-vz/core.