Skip to content

API Biểu đồ phân tán

Dùng biểu đồ này khi câu hỏi là "hai con số này có liên quan với nhau không?" - các prop và engine ở bên dưới; câu trả lời nằm ở bản demo Biểu đồ phân tán.

Import

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

const chart = mountScatterChart(el, props);

Props

PropTypeDefaultDescription
dataSet*ScatterDataPoint[]-Array of points to plot in the cloud
titlestring-Optional chart title rendered above the plot
xAxisDataType"date_annual" | "date_monthly" | "number""number"number / date / band (categorical) for x. y is always linear.
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
xAxisDomain[number, number] | string[]-Fix the x-axis range ([min,max]); for band x, the ordered category labels (string[]).
yAxisDomain[number, number]-Fix the y-axis range as [min, max] instead of deriving it from the data
sizeRange[number, number][4, 20][minRadius, maxRadius] px for the size scale (default [4, 20]).
ticksnumber5Approximate number of axis ticks to generate
tickValuesArray<number | Date>-Explicit tick values, overriding the generated ones
filterFilter-Top-N / sort filter applied to the data before rendering
timelineboolean | TimelinePeriodConfig-Opt-in "play through years": snapshots one period at a time over the distinct per-row `date` values, with a headless controller (`chart.timeline()`) plus an optional built-in play button + scrubber. Off by default; requires rows with `date`. The user's `filter` still applies within each period.
tooltipFormatter(d: ScatterDataPoint) => string-Returns custom tooltip HTML for a hovered datum (sanitized before it is inserted)
isLoadingboolean-Show the loading overlay and skip the no-data check (legacy michi-vz parity).
isNodata| boolean | ((dataSet: ScatterDataPoint[] | null | undefined) => boolean)-No-data override: boolean, or a predicate on the data; default = empty data.
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.
onHighlightItem(labels: string[]) => void-Called when the hovered/highlighted label(s) change
showCrosshairbooleanfalseShow a crosshair overlay tracking the hovered point. Default false.
crosshairLabelsbooleanfalseRender axis-badge value readouts at the crosshair intersection. Default false.
crosshairLineStyle"solid" | "dashed"-"dashed" → both hover+pinned dashed; "solid" → both solid; undefined → hover dashed.
crosshairSpan"full" | "half""full""full" → both crosshair lines span the whole plot; "half" → an L-shaped arm from the bubble to the two axes. Default "full".
crosshairLabelPlacement"auto" | "fixed"-"auto" → collision-flip badges; "fixed" → anchor to bottom-left. Default "auto".
dScaleLegend{ title?: string; valueFormatter?: (d: number) => string }-Bubble-size reference legend (half-arc trio + domain labels).
yTicksQtynumber-Override the y-axis tick count (scale.ticks(n)); falls back to `ticks`.
showGridboolean | { x?: boolean; y?: boolean }-Grid lines per axis: boolean → both; { x?, y? } → per-axis (each defaults true). Default both on.
pinIconboolean-Pass false to suppress the sticky-tooltip pin icon. Default: shown (no-op until an icon exists).
pointLabelsboolean | ScatterPointLabelsConfig-Per-point text label (the point's `label` by default). Omitted, or `false`, is a byte-for-byte no-op - zero `.mv-point-label` DOM, default off. Placement is a SIMPLIFIED right-of-point + overlap-hide strategy: each label anchors just to the right of its point (at the current z/draw-order position - see `drawOrder`), and a label is skipped entirely if its estimated bounding box would overlap an already-placed label's box (points processed in that same draw order, so the result never depends on unordered iteration). This intentionally diverges from the legacy sdg-trade Scatterplot (`components/Charts/Scatterplot/Chart.js`), which used d3-voronoi to pick a non-colliding label DIRECTION (right/left/top/ bottom, from the point toward its voronoi cell's centroid) and hid a label only when its voronoi cell's polygon area was <= 10000px². No d3-voronoi dependency was added for this port (none allowed) - the parity bar accepts a cosmetically different placement; the requirement is that labels exist and don't visually collide. Painted on the SVG scaffold layer unconditionally (same treatment as the title/axes and ComparableBar's `deltaIndicator`), so labels look identical whichever `renderer` painted the points themselves.
drawOrder"sizeDescending" | "sizeAscending""sizeDescending"Draw-order for overlapping bubbles. Two values, no "off" state - the chart always draws bubbles in SOME order, so the default just names the pre-existing one instead of pretending there's no ordering at all. - `"sizeDescending"` (default, omitted resolves here): today's existing, zero-diff behaviour. `buildScatterRenderModel` has, since before this prop existed, unconditionally sorted points largest-first whenever radii vary, so smaller bubbles paint over larger ones (readability: small bubbles don't get hidden behind big ones). - `"sizeAscending"`: a genuine opt-in that flips the comparator so the LARGEST bubble draws LAST / on top instead. This reproduces the actual legacy sdg-trade z-order, confirmed by reading `sdg-trade/.../Scatterplot/Scatterplot.js` (`data.sort((a,b) => a[rValueKey]-b[rValueKey])` - ascending by raw size) and `.../Scatterplot/Chart.js` (draws circles via `data.map` in that array order; later SVG siblings paint over earlier ones) - net effect: the LARGEST bubble is drawn last and ends up on top there, the opposite of this chart's own default. Use `"sizeAscending"` for true legacy parity.
svgChildrenstring-Pre-serialised SVG markup injected as direct <svg> children (the React wrapper fills this from `children`).
Common props - shared by every chart (14)
PropTypeDefaultDescription
widthnumber900Chart width in pixels
heightnumber480Chart 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
rendererRenderer"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, ...)

Events

Web component phát ra các CustomEvent nổi bọt (bubbling) sau đây (engine cũng cung cấp tương đương qua các callback on* trong bảng ở trên):

EventDetailKích hoạt khi
michi-vz:highlightstring[]khi trạng thái tô sáng hover thay đổi
michi-vz:colormappingRecord<string, string>khi một color mapping được tạo ra
michi-vz:dataprocessedChartContextkhi dữ liệu được xử lý (lại)
michi-vz:datawarningDataWarning[]khi phát hiện cảnh báo về dữ liệu đầu vào

getContext()

mountScatterChart(el, props).getContext() trả về một ScatterChartContext không phụ thuộc bộ dựng (số liệu thống kê có cấu trúc + một bản tóm tắt ngôn ngữ tự nhiên có tính xác định + một bảng a11y). Xem ngữ cảnh LLM.

Source

Các prop được định kiểu là ScatterChartProps trong @michi-vz/core.