網站導覽

v2.1.0
資料顯示

圖表

用單一 SVG 呈現數值,適應任何寬度,支援從折線圖到旭日圖等二十多種圖表。

本頁內容

依讀者想了解的問題選擇圖表形式,例如折線圖、長條圖、圓環圖、直方圖或漏斗圖,總共有二十多種。每種圖表都以單一 SVG 配合可用寬度。刻度上的圖形以百分比定位,繪圖區無論拉得多寬,線條粗細和文字大小都維持原樣。單一資料序列使用前景色,如同進度條以此色填滿。有多個資料序列時,則使用類別配色。每個資料點都是清單項目,並以文字說明其數值。

圖表

<div class="card max-w(560) mx-auto">  <div class="card-header">    <h3 class="card-title">Requests</h3>    <p class="card-description">Millions per month, by region</p>  </div>  <figure class="chart" id="requests"></figure></div><script>addEventListener('DOMContentLoaded', function () {MasterUI.chart(document.getElementById('requests'), {  type: 'area',  label: 'Requests per month by region, in millions',  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],  series: [    { name: 'Tokyo', values: [32, 36, 34, 41, 46, 44, 52, 56, 54, 61, 68, 72] },    { name: 'Frankfurt', values: [12, 14, 18, 17, 22, 26, 25, 30, 34, 33, 39, 42] }  ]})})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { Chart } from './ui/chart'<div className="card max-w(560) mx-auto">  <div className="card-header">    <h3 className="card-title">Requests</h3>    <p className="card-description">Millions per month, by region</p>  </div>  <Chart    id="requests"    type="area"    label="Requests per month by region, in millions"    labels={['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']}    series={[      { name: 'Tokyo', values: [32, 36, 34, 41, 46, 44, 52, 56, 54, 61, 68, 72] },      { name: 'Frankfurt', values: [12, 14, 18, 17, 22, 26, 25, 30, 34, 33, 39, 42] }    ]}  /></div>
<script>  import Chart from './ui/Chart.svelte'</script><div class="card max-w(560) mx-auto">  <div class="card-header">    <h3 class="card-title">Requests</h3>    <p class="card-description">Millions per month, by region</p>  </div>  <Chart    id="requests"    type="area"    label="Requests per month by region, in millions"    labels={['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']}    series={[      { name: 'Tokyo', values: [32, 36, 34, 41, 46, 44, 52, 56, 54, 61, 68, 72] },      { name: 'Frankfurt', values: [12, 14, 18, 17, 22, 26, 25, 30, 34, 33, 39, 42] }    ]}  /></div>
<script setup>import Chart from './ui/Chart.vue'</script><template>  <div class="card max-w(560) mx-auto">    <div class="card-header">      <h3 class="card-title">Requests</h3>      <p class="card-description">Millions per month, by region</p>    </div>    <Chart      id="requests"      type="area"      label="Requests per month by region, in millions"      :labels="['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']"      :series="[        { name: 'Tokyo', values: [32, 36, 34, 41, 46, 44, 52, 56, 54, 61, 68, 72] },        { name: 'Frankfurt', values: [12, 14, 18, 17, 22, 26, 25, 30, 34, 33, 39, 42] }      ]"    />  </div></template>
將指標移到某個月份,或按 Tab 再用方向鍵選取,即可查看數值。取消勾選圖例項目可隱藏對應的資料序列。

#繪製方式

繪圖區使用沒有 viewBox 的 <svg>,寬度填滿可用空間,高度由 --chart-height 設定,預設為 14rem。極細線、刻度線、長條和圓點都以繪圖區的百分比定位,所以 x="42%" 的長條在任何寬度下都位於 42% 的位置,圓角半徑和文字大小也維持原樣。

只有必須用路徑表示的圖形,也就是線條、區域或扇形,才會繪製在 chart-canvas 裡。這是一個座標範圍為 100 × 100 的巢狀 SVG,會拉伸至填滿繪圖區。筆畫粗細不隨之縮放,所以無論卡片寬窄,線寬都是 --chart-stroke。

寬度改變時,圖表無須測量尺寸或重新繪製,因此伺服器、框架元件和行為都會產生相同的標記。圖表會填滿可用寬度。若將它和其他項目並排,請指定寬度或讓它伸展以填滿剩餘空間。

#繪製圖表

圖表行為會將圖表寫入帶有 chart 類別的元素。label 說明圖表呈現的內容與單位,labels 為刻度上的各個位置命名,而每個資料序列在每個位置各有一個數值。

app.js
import { chart } from '@master/ui/behaviors/chart.js'chart(document.querySelector('.chart'), {  type: 'line',  label: 'Latency by region, in milliseconds',  labels: ['Jan', 'Feb', 'Mar', 'Apr'],  series: [    { name: 'Tokyo', values: [42, 44, 41, 47] },    { name: 'Frankfurt', values: [61, 58, 63, 66] },  ],})

在伺服器端,chartMarkup() 會以字串傳回相同的圖表,其中的文字均已跳脫。將字串放入元素後,讀者在任何腳本執行前就能閱讀頁面上的圖表。chartLayout() 會傳回繪圖所用的資料,包括刻度範圍與刻度、各資料序列的路徑,以及每個資料點的圖形標記與描述文字。

server.js
import { chartMarkup } from '@master/ui/behaviors/chart.js'const html = `<figure class="chart">${chartMarkup({ type: 'bar', label, labels, series })}</figure>`

對該元素呼叫 chart() 且不傳入資料序列,即可讓既有的圖表標記具備互動行為。@master/ui/behaviors 的 attach() 則會為頁面上的所有圖表加上互動行為。

#只載入頁面使用的圖表形式

chart.js 包含所有形式,壓縮程式碼並以 gzip 壓縮後約為 16 kB。若頁面只繪製一兩種圖表,可以只載入需要的形式。chart-core.js 約為 6 kB,本身未包含任何圖表形式。各形式各有模組,可傳給 chartForms()。折線圖、區域圖和長條圖共用刻度,三者合計增加約 2 kB,其餘形式各增加不到 1 kB。

app.js
import { chartCore, chartForms } from '@master/ui/behaviors/chart-core.js'import { chartCartesian } from '@master/ui/behaviors/chart-cartesian.js'chartForms(chartCartesian)chartCore(document.querySelector('.chart'), { type: 'line', label, labels, series })
模組繪製內容
chart-cartesian.jsline, area, bar
chart-scatter.jsscatter
chart-pie.jspie, donut
chart-rings.js, chart-radar.js, chart-sunburst.jsrings, radar, sunburst
chart-waterfall.js, chart-range.jswaterfall; range, dumbbell
chart-slope.js, chart-bump.jsslope, bump
chart-marimekko.js, chart-funnel.js, chart-waffle.js, chart-treemap.jsmarimekko, funnel, waffle, treemap
chart-histogram.js, chart-box.js, chart-heatmap.jshistogram, box, heatmap

若指定了尚未載入的圖表類型,就會立即擲出錯誤,指出應匯入的模組。

#圖表形式

每種圖表都有專屬頁面,提供範例與相關選項。

形式type用途
折線圖line以線段依序連接資料點,呈現數值變化。
面積圖area在折線下方填上同色的淡色,可單獨呈現,也可堆疊以顯示總量。
斜率圖slope從線條的斜率與交會看出兩個時間點之間的上升、下降與相對位置變化。
排名變化圖bump以線條呈現各項目的排名變化,線條交會處表示排名互換。
長條圖bar用共用基準線的長條比較數量,可並排、堆疊或橫向排列。
雷達圖radar沿共用指標比較多個項目,每個項目各以環繞同一個中心的輪廓表示。
瀑布圖waterfall用逐步增加與減少的數值,呈現起始值如何變成最終值。
區間圖range呈現各區間的起點與終點。
啞鈴圖dumbbell以線段連接各項目的兩個數值,凸顯兩者之間的差距。
圓餅圖pie用扇形呈現整體的組成。
圓環圖donut在中央數值周圍呈現整體的各個部分。
多環圖rings每個讀值各用一個環,以填滿的比例表示讀值占總量的多少。
馬賽克圖marimekko各長條的寬度反映總量,條內再依組成比例分割。
漏斗圖funnel呈現流程的各個階段,寬度逐階縮小。
華夫格圖waffle以一百個方格呈現整體,每格代表 1%。
樹狀矩形圖treemap用矩形區塊呈現整體的各個部分,區塊面積反映各自的占比。
旭日圖sunburst用兩層圓環呈現整體、各個部分,以及各部分的細項。
直方圖histogram用易讀的數值作為組界,將讀值分入各組距,並以柱高表示各組的筆數,以呈現分布。
盒鬚圖box每組以五個統計量呈現分布,畫出盒體、中位數與兩端的鬚線。
熱圖heatmap在兩個維度上呈現資料模式,以格子的色深表示數值。
散佈圖scatter比較兩項指標之間的關係,每個項目以一個點表示。

折線圖、區域圖和長條圖可以共用刻度並放在同一張圖表中。為資料序列指定自己的 type,就會按指定形式繪製,例如在長條上疊加折線。

#數值提示與鍵盤操作

chart-tip 是數值提示。它先顯示資料點名稱,再逐列顯示各資料序列的色線、名稱與數值。提示會出現在資料點旁空間較多的一側,並依自身高度調整垂直位置,因此能留在繪圖區內,無須由腳本定位。互動行為會從資料點的圖形標記取得內容,並透過 --chart-x、--chart-y 和 --chart-reach 傳遞資料點的位置。

無論有多少資料點,整個繪圖區在 Tab 鍵巡覽順序中都只占一站。按方向鍵可逐點移動並查看數值提示,也可以用手指沿著圖表滑動。

按鍵動作
Tab進入繪圖區時,焦點落在上次停留的資料點,沒有時則落在第一個資料點,並顯示其數值提示;接著移到圖例的核取方塊
ArrowRight, ArrowDown移到下一個資料點並顯示其數值提示
ArrowLeft, ArrowUp移到前一個資料點
Home, End移到第一個或最後一個資料點
Escape隱藏數值提示,焦點留在該資料點上
Space在圖例的核取方塊上,顯示或隱藏對應的序列

#圖例

有兩個以上資料序列的圖表會顯示圖例,讓使用者也能透過名稱辨識資料序列。每個圖例項目都是包住核取方塊的標籤,可按 Tab 移入焦點,再按空白鍵切換。取消勾選後,對應的資料序列會從圖表隱藏,刻度會配合剩餘資料調整,其他序列則保留原有色彩。單一資料序列的圖表由標題說明繪製內容,因此省略圖例。

toggle: false 會將圖例顯示為一般清單。若圖表周圍的文字已說明各資料序列的名稱,可用 legend: false 省略圖例。圖表的值是隱藏的資料序列名稱。可從 chart() 的回傳結果讀取這個值,也可從外部設定它來隱藏資料序列。

#色彩

單一資料序列使用前景色 --chart-color。多個資料序列或整體的各個部分,依固定順序使用類別色:藍、橘、藍綠、紫、琥珀、粉紅、綠和天藍。無論淺色或深色配置,常見色覺辨識障礙的使用者仍能區分相鄰的色彩。超過八個就會循環使用配色,可將其餘項目合併為「其他」,或另畫一張圖表。

若同一項目在各處都要使用同一色彩,請為資料序列指定 category。例如東京無論排在清單的哪個位置,在圖表、徽章和表格列中都使用藍色。資料序列不使用狀態色。若某個序列的表現不佳,請用文字說明。

#刻度與數值

刻度從零起算,有負值時則從零以下起算,並以高於最大值的易讀數值作為上限。預設約分成四個間距。可用 min 和 max 固定兩端,再用 ticks 指定其他間距數。長條圖的刻度應從零開始,因為長條的長度代表數值。

format 設定數值提示與長條末端的數值格式,tickFormat 設定刻度的數字格式。刻度在 10,000 以下顯示完整數字,超過時採用精簡格式。兩者均接收數字並傳回字串。locale 是用於數字格式的 BCP 47 語言標籤,預設為 en-US。由伺服器產生圖表時,請指定此選項,讓伺服器與用戶端使用相同的格式。

選項預設
type'bar'圖表形式中列出的其中一種類型
label無繪圖區的無障礙名稱,說明圖表呈現的內容與單位
labels[]刻度各處、雷達圖周圍或熱圖各欄上方的名稱
series[]每個資料序列都有 name,並依圖表形式提供 values、value、points、ranges 或 children。也可選填 category、type、low、high,以及環形量表的 max
stackedfalse堆疊長條或區域。'percent' 將各組堆疊調整為 100%,'stream' 使堆疊區域沿中線置中
horizontalfalse橫向繪製長條、範圍、啞鈴與盒鬚
mark'bar''lollipop' 用末端帶圓點的線段表示長條
curve'smooth'smooth、linear 或 step
min, max, ticks自動配合資料、4刻度的兩端與約略的間距數。散佈圖的橫軸刻度使用 xMin、xMax 和 xTicks
axistrue是否顯示刻度數字。用於區塊內的小圖表時,可設為 false 以只保留極細線
format, tickFormat依語言標籤數值與刻度的顯示格式。散佈圖的橫軸刻度使用 xFormat
dots, valuesfalse標示折線上的每個資料點,以及顯示各長條的數值
current無標有 aria-current 的資料點索引
legend, toggle兩個以上資料序列時顯示、true是否顯示圖例,以及圖例項目是否使用核取方塊
hole, center.7、無圓環圖的中空比例,以及圓環圖或環形量表的中央內容
total無瀑布圖最後一個長條的名稱
bins依資料筆數直方圖將讀值分成的約略組數
ascendingfalse在排名變化圖中,數值最低者排第一
words英文盒鬚圖五個統計量的名稱:min、q1、median、q3 和 max
hidden[]隱藏的資料序列名稱
locale'en-US'用於數字格式的 BCP 47 語言標籤
draw無由自行繪製圖表的渲染器接手,呼叫時會傳入隱藏的資料序列名稱

#無須腳本

伺服器產生的標記已包含完整圖表,無須執行腳本。螢幕閱讀器仍可讀出各資料點的數值,而樣式表即可回應指標,顯示極細線與圓點,並淡化其他長條。腳本會加上數值提示、鍵盤操作和圖例切換功能。

以標記撰寫

<figure class="chart max-w(400) mx-auto" style="--chart-height: 10rem">  <div class="chart-body" style="--chart-gutter: 2">    <svg class="chart-plot" role="list" aria-label="Deployments per day, Monday to Friday">      <g aria-hidden="true">        <line class="chart-grid chart-grid-base" x1="0" y1="100%" x2="100%" y2="100%" />        <line class="chart-grid" x1="0" y1="75%" x2="100%" y2="75%" />        <line class="chart-grid" x1="0" y1="50%" x2="100%" y2="50%" />        <line class="chart-grid" x1="0" y1="25%" x2="100%" y2="25%" />        <line class="chart-grid" x1="0" y1="0%" x2="100%" y2="0%" />        <text class="chart-tick chart-tick-y" x="0" y="100%">0</text>        <text class="chart-tick chart-tick-y" x="0" y="75%">20</text>        <text class="chart-tick chart-tick-y" x="0" y="50%">40</text>        <text class="chart-tick chart-tick-y" x="0" y="25%">60</text>        <text class="chart-tick chart-tick-y" x="0" y="0%">80</text>        <text class="chart-tick chart-tick-x" x="10%" y="100%">Mon</text>        <text class="chart-tick chart-tick-x" x="30%" y="100%">Tue</text>        <text class="chart-tick chart-tick-x" x="50%" y="100%">Wed</text>        <text class="chart-tick chart-tick-x" x="70%" y="100%">Thu</text>        <text class="chart-tick chart-tick-x" x="90%" y="100%">Fri</text>      </g>      <g class="chart-point" role="listitem" aria-label="Mon: 42">        <rect class="chart-hit" x="0%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="3.8%" y="47.5%" width="12.4%" height="52.5%" />      </g>      <g class="chart-point" role="listitem" aria-label="Tue: 58">        <rect class="chart-hit" x="20%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="23.8%" y="27.5%" width="12.4%" height="72.5%" />      </g>      <g class="chart-point" role="listitem" aria-label="Wed: 36">        <rect class="chart-hit" x="40%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="43.8%" y="55%" width="12.4%" height="45%" />      </g>      <g class="chart-point" role="listitem" aria-label="Thu: 71">        <rect class="chart-hit" x="60%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="63.8%" y="11.25%" width="12.4%" height="88.75%" />      </g>      <g class="chart-point" role="listitem" aria-label="Fri: 64">        <rect class="chart-hit" x="80%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="83.8%" y="20%" width="12.4%" height="80%" />      </g>    </svg>  </div></figure>
<figure className="chart max-w(400) mx-auto" style={{ '--chart-height': '10rem' } as React.CSSProperties}>  <div className="chart-body" style={{ '--chart-gutter': '2' } as React.CSSProperties}>    <svg className="chart-plot" role="list" aria-label="Deployments per day, Monday to Friday">      <g aria-hidden="true">        <line className="chart-grid chart-grid-base" x1="0" y1="100%" x2="100%" y2="100%" />        <line className="chart-grid" x1="0" y1="75%" x2="100%" y2="75%" />        <line className="chart-grid" x1="0" y1="50%" x2="100%" y2="50%" />        <line className="chart-grid" x1="0" y1="25%" x2="100%" y2="25%" />        <line className="chart-grid" x1="0" y1="0%" x2="100%" y2="0%" />        <text className="chart-tick chart-tick-y" x="0" y="100%">0</text>        <text className="chart-tick chart-tick-y" x="0" y="75%">20</text>        <text className="chart-tick chart-tick-y" x="0" y="50%">40</text>        <text className="chart-tick chart-tick-y" x="0" y="25%">60</text>        <text className="chart-tick chart-tick-y" x="0" y="0%">80</text>        <text className="chart-tick chart-tick-x" x="10%" y="100%">Mon</text>        <text className="chart-tick chart-tick-x" x="30%" y="100%">Tue</text>        <text className="chart-tick chart-tick-x" x="50%" y="100%">Wed</text>        <text className="chart-tick chart-tick-x" x="70%" y="100%">Thu</text>        <text className="chart-tick chart-tick-x" x="90%" y="100%">Fri</text>      </g>      <g className="chart-point" role="listitem" aria-label="Mon: 42">        <rect className="chart-hit" x="0%" y="0" width="20%" height="100%" />        <rect className="chart-bar" x="3.8%" y="47.5%" width="12.4%" height="52.5%" />      </g>      <g className="chart-point" role="listitem" aria-label="Tue: 58">        <rect className="chart-hit" x="20%" y="0" width="20%" height="100%" />        <rect className="chart-bar" x="23.8%" y="27.5%" width="12.4%" height="72.5%" />      </g>      <g className="chart-point" role="listitem" aria-label="Wed: 36">        <rect className="chart-hit" x="40%" y="0" width="20%" height="100%" />        <rect className="chart-bar" x="43.8%" y="55%" width="12.4%" height="45%" />      </g>      <g className="chart-point" role="listitem" aria-label="Thu: 71">        <rect className="chart-hit" x="60%" y="0" width="20%" height="100%" />        <rect className="chart-bar" x="63.8%" y="11.25%" width="12.4%" height="88.75%" />      </g>      <g className="chart-point" role="listitem" aria-label="Fri: 64">        <rect className="chart-hit" x="80%" y="0" width="20%" height="100%" />        <rect className="chart-bar" x="83.8%" y="20%" width="12.4%" height="80%" />      </g>    </svg>  </div></figure>
<figure class="chart max-w(400) mx-auto" style="--chart-height: 10rem">  <div class="chart-body" style="--chart-gutter: 2">    <svg class="chart-plot" role="list" aria-label="Deployments per day, Monday to Friday">      <g aria-hidden="true">        <line class="chart-grid chart-grid-base" x1="0" y1="100%" x2="100%" y2="100%" />        <line class="chart-grid" x1="0" y1="75%" x2="100%" y2="75%" />        <line class="chart-grid" x1="0" y1="50%" x2="100%" y2="50%" />        <line class="chart-grid" x1="0" y1="25%" x2="100%" y2="25%" />        <line class="chart-grid" x1="0" y1="0%" x2="100%" y2="0%" />        <text class="chart-tick chart-tick-y" x="0" y="100%">0</text>        <text class="chart-tick chart-tick-y" x="0" y="75%">20</text>        <text class="chart-tick chart-tick-y" x="0" y="50%">40</text>        <text class="chart-tick chart-tick-y" x="0" y="25%">60</text>        <text class="chart-tick chart-tick-y" x="0" y="0%">80</text>        <text class="chart-tick chart-tick-x" x="10%" y="100%">Mon</text>        <text class="chart-tick chart-tick-x" x="30%" y="100%">Tue</text>        <text class="chart-tick chart-tick-x" x="50%" y="100%">Wed</text>        <text class="chart-tick chart-tick-x" x="70%" y="100%">Thu</text>        <text class="chart-tick chart-tick-x" x="90%" y="100%">Fri</text>      </g>      <g class="chart-point" role="listitem" aria-label="Mon: 42">        <rect class="chart-hit" x="0%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="3.8%" y="47.5%" width="12.4%" height="52.5%" />      </g>      <g class="chart-point" role="listitem" aria-label="Tue: 58">        <rect class="chart-hit" x="20%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="23.8%" y="27.5%" width="12.4%" height="72.5%" />      </g>      <g class="chart-point" role="listitem" aria-label="Wed: 36">        <rect class="chart-hit" x="40%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="43.8%" y="55%" width="12.4%" height="45%" />      </g>      <g class="chart-point" role="listitem" aria-label="Thu: 71">        <rect class="chart-hit" x="60%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="63.8%" y="11.25%" width="12.4%" height="88.75%" />      </g>      <g class="chart-point" role="listitem" aria-label="Fri: 64">        <rect class="chart-hit" x="80%" y="0" width="20%" height="100%" />        <rect class="chart-bar" x="83.8%" y="20%" width="12.4%" height="80%" />      </g>    </svg>  </div></figure>
<template>  <figure class="chart max-w(400) mx-auto" style="--chart-height: 10rem">    <div class="chart-body" style="--chart-gutter: 2">      <svg class="chart-plot" role="list" aria-label="Deployments per day, Monday to Friday">        <g aria-hidden="true">          <line class="chart-grid chart-grid-base" x1="0" y1="100%" x2="100%" y2="100%" />          <line class="chart-grid" x1="0" y1="75%" x2="100%" y2="75%" />          <line class="chart-grid" x1="0" y1="50%" x2="100%" y2="50%" />          <line class="chart-grid" x1="0" y1="25%" x2="100%" y2="25%" />          <line class="chart-grid" x1="0" y1="0%" x2="100%" y2="0%" />          <text class="chart-tick chart-tick-y" x="0" y="100%">0</text>          <text class="chart-tick chart-tick-y" x="0" y="75%">20</text>          <text class="chart-tick chart-tick-y" x="0" y="50%">40</text>          <text class="chart-tick chart-tick-y" x="0" y="25%">60</text>          <text class="chart-tick chart-tick-y" x="0" y="0%">80</text>          <text class="chart-tick chart-tick-x" x="10%" y="100%">Mon</text>          <text class="chart-tick chart-tick-x" x="30%" y="100%">Tue</text>          <text class="chart-tick chart-tick-x" x="50%" y="100%">Wed</text>          <text class="chart-tick chart-tick-x" x="70%" y="100%">Thu</text>          <text class="chart-tick chart-tick-x" x="90%" y="100%">Fri</text>        </g>        <g class="chart-point" role="listitem" aria-label="Mon: 42">          <rect class="chart-hit" x="0%" y="0" width="20%" height="100%" />          <rect class="chart-bar" x="3.8%" y="47.5%" width="12.4%" height="52.5%" />        </g>        <g class="chart-point" role="listitem" aria-label="Tue: 58">          <rect class="chart-hit" x="20%" y="0" width="20%" height="100%" />          <rect class="chart-bar" x="23.8%" y="27.5%" width="12.4%" height="72.5%" />        </g>        <g class="chart-point" role="listitem" aria-label="Wed: 36">          <rect class="chart-hit" x="40%" y="0" width="20%" height="100%" />          <rect class="chart-bar" x="43.8%" y="55%" width="12.4%" height="45%" />        </g>        <g class="chart-point" role="listitem" aria-label="Thu: 71">          <rect class="chart-hit" x="60%" y="0" width="20%" height="100%" />          <rect class="chart-bar" x="63.8%" y="11.25%" width="12.4%" height="88.75%" />        </g>        <g class="chart-point" role="listitem" aria-label="Fri: 64">          <rect class="chart-hit" x="80%" y="0" width="20%" height="100%" />          <rect class="chart-bar" x="83.8%" y="20%" width="12.4%" height="80%" />        </g>      </svg>    </div>  </figure></template>
無須腳本,長條以百分比定位,指標停在某個長條上時,其餘長條會淡化。

#動態效果

圖形標記初次顯示時會逐步繪出。長條依序從基準線升起,折線從起點延伸,扇形與雷達圖的圖形從中心展開,環形量表則逐步填滿。數值提示會在資料點之間滑動,極細線、圓點和長條淡化等醒目效果則會立即跟上使用者的操作。啟用減少動態效果時,圖形會直接以完成狀態顯示,數值提示也會立即換位。

#瀏覽器功能

  • 長條的圓角與升起效果以 SVG 圖形上的 clip-path 實作。若瀏覽器不支援以 CSS 形狀裁切 SVG 圖形,長條會以直角和完整長度顯示。
  • 區域的漸淡效果由路徑上的 mask-image 實作。缺少此功能時,整塊區域會以均勻的淡色顯示。
  • 圓點半徑使用 CSS 的 r 屬性,由 --chart-dot 設定。缺少此功能時,圓點會保留標記中指定的半徑。
  • 減少標籤數量由繪圖區主體的容器查詢控制。缺少容器查詢時,會保留所有標籤。
  • 初次繪出的效果使用 @starting-style。缺少此功能時,圖形標記會直接以完成狀態顯示。

#圖表的適用範圍

圖表適合呈現數百個圖形標記,每個標記都是讀者可存取的元素。若要處理數千個資料點、串流數值、縮放、框選、地圖或 K 線圖,請使用在 Canvas 上繪製的圖表引擎。若只需要呈現少量資訊,也有更精簡的元件可用。用走勢圖在句子中呈現趨勢,用統計數值呈現單一數字,用量表或儀表呈現單一讀值,用組成長條在一根長條上呈現總量的組成,或用熱圖呈現許多小數值形成的模式。請參閱圖表指南選擇合適的元件。

#無障礙

  • 為 label 撰寫一句話,說明測量的內容和單位。這句話是繪圖區的名稱,而繪圖區會以清單呈現。
  • 每個資料點都是以其數值命名的清單項目,例如「週四:東京 71、大阪 49」。無須腳本或表格,螢幕閱讀器就能像讀取清單一樣讀取圖表。極細線、刻度線和數值提示會對螢幕閱讀器隱藏,因為資料點已提供相同資訊。
  • 數值提示方便讀者直接查看數值。將指標停在資料點上、讓資料點取得焦點或用手指觸碰時都會顯示,按 Esc 即可隱藏。
  • 除了色彩,圖例也會標示資料序列的名稱,數值提示則會並列顯示名稱與數值。類別色不代表狀態。
  • 資料點取得焦點時,焦點外框會沿著其帶狀區域、圓點、扇形或圓環的輪廓繪製。
  • 在強制色彩模式下,前景色與極細線會採用系統色,焦點則使用系統的醒目提示色。各資料序列會保留指定色彩,請在圖例中標示其名稱。
  • 無論使用哪種語言,刻度都從左側開始。名稱、數值與圖例遵循頁面的書寫方向。

#React、Svelte 與 Vue

chart 元件依 chartLayout() 產生圖表,因此伺服器首次送出的 HTML 就包含圖表。元件也會加上互動行為,以填入數值提示並回應按鍵。元件以上述選項作為 props,其值為隱藏的資料序列名稱。使用 npx master-ui add chart 將元件複製到專案。請參閱 React、Svelte 與 Vue 了解如何建置與使用元件。

ui/chart.tsx
'use client'import { useMemo, useState, type ComponentProps, type CSSProperties } from 'react'import { chart, chartLayout, type ChartConfig, type ChartLayout, type ChartMark, type ChartPoint, type ChartSeries } from '@master/ui/behaviors/chart.js'import { useBehavior } from './use-behavior'export type { ChartConfig, ChartSeries }export interface ChartProps extends Omit<ComponentProps<'figure'>, 'defaultValue' | 'children' | 'ref'>, Omit<ChartConfig, 'hidden'> {  /** The names of the hidden series, as the legend's unchecked boxes say. None by default. */  value?: string[]  defaultValue?: string[]  onValueChange?: (value: string[]) => void}const style = (properties: Record<string, string | number>) => properties as CSSPropertiesconst drawn = (item: ChartMark, index: number) => {  const className = item.category ? `${item.classes} category-${item.category}` : item.classes  const named = { 'data-name': item.name, 'data-value': item.name === undefined ? undefined : item.value ?? '' }  // What only this mark knows, a share of its color or a bubble's size, goes on as a custom property.  const known = item.tone === undefined && item.size === undefined ? undefined : style({ ...(item.tone === undefined ? null : { '--chart-tone': `${item.tone}%` }), ...(item.size === undefined ? null : { '--chart-dot': `${item.size}px` }) })  if (item.kind === 'bar') return <rect className={className} x={item.x} y={item.y} width={item.width} height={item.height} style={known} {...named} key={index} />  if (item.kind === 'dot') return <circle className={className} cx={item.cx} cy={item.cy} r={item.r || undefined} style={known} {...named} key={index} />  if (item.kind === 'line') return <line className={className} x1={item.x1} y1={item.y1} x2={item.x2} y2={item.y2} {...named} key={index} />  return <path className={className} d={item.d} strokeWidth={item.stroke || undefined} pathLength={item.kind === 'arc' ? 1 : undefined} style={known} {...named} key={index} />}const hit = (area: NonNullable<ChartPoint['hit']>) => 'd' in area  ? <path className="chart-hit" d={area.d} />  : 'r' in area    ? <circle className="chart-hit" cx={area.cx} cy={area.cy} r={area.r} />    : <rect className="chart-hit" x={area.x} y={area.y} width={area.width} height={area.height} />const entry = (key: ChartLayout['legend'][number]) => (  <><span className={key.mark} />{key.name}{key.value === undefined ? null : <span className="chart-key-value">{key.value}</span>}</>)/** * A chart, in every form the chart behavior lays out, in one SVG. React writes it from * `chartLayout()`, the same layout the behavior writes, so it is in the first HTML; the behavior shows the * readout of the point under the pointer or the keys, and says which series the legend hides. */export function Chart({ type, label, labels, series, stacked, horizontal, mark, curve, min, max, ticks, axis, format, tickFormat, xMin, xMax, xTicks, xFormat, dots, values, current, legend, toggle, legendLabel, hole, center, total, bins, ascending, words, locale, value, defaultValue, onValueChange, className, ...root }: ChartProps) {  const [first] = useState(() => value ?? defaultValue ?? [])  const [hidden, setHidden] = useState(first)  const layout = useMemo(    () => chartLayout({ type, label, labels, series, stacked, horizontal, mark, curve, min, max, ticks, axis, format, tickFormat, xMin, xMax, xTicks, xFormat, dots, values, current, legend, toggle, legendLabel, hole, center, total, bins, ascending, words, locale, hidden }),    [type, label, labels, series, stacked, horizontal, mark, curve, min, max, ticks, axis, format, tickFormat, xMin, xMax, xTicks, xFormat, dots, values, current, legend, toggle, legendLabel, hole, center, total, bins, ascending, words, locale, hidden],  )  const ref = useBehavior(chart, { hidden: first, draw: setHidden }, { value, defaultValue, onValueChange })  // The first point is the stop in the tab order of the first render; the behavior moves it from there.  const points = layout.points.map((point, index) => (    <g className="chart-point" role="listitem" aria-label={point.text} aria-current={point.current ? 'true' : undefined} data-label={point.label} tabIndex={index ? -1 : 0} style={style({ '--chart-x': point.x, '--chart-y': point.y, '--chart-reach': point.reach, '--chart-index': point.index })} key={point.index}>      {point.hit ? hit(point.hit) : null}      {point.cursor ? <line className="chart-cursor" x1={point.cursor.x1} y1={point.cursor.y1} x2={point.cursor.x2} y2={point.cursor.y2} /> : null}      {point.marks.map(drawn)}    </g>  ))  const paths = layout.paths.map((path, index) => <path className={path.category ? `${path.classes} category-${path.category}` : path.classes} d={path.d} style={path.tone === undefined ? undefined : style({ '--chart-tone': `${path.tone}%` })} key={index} />)  return (    <figure className={className ? `chart ${className}` : 'chart'} ref={ref} {...root}>      <div className="chart-body" style={style({ '--chart-gutter': layout.gutter, '--chart-tail': layout.tail })}>        <svg className={layout.classes} role="list" aria-label={layout.label || undefined}>          <g aria-hidden="true">            {layout.grid.map((line, index) => <line className={line.base ? 'chart-grid chart-grid-base' : 'chart-grid'} x1={line.x1} y1={line.y1} x2={line.x2} y2={line.y2} key={index} />)}            {layout.ticks.map((tick, index) => <text className={tick.classes} x={tick.x} y={tick.y} style={tick.at ? style({ '--chart-x': tick.at[0], '--chart-y': tick.at[1] }) : undefined} key={index}>{tick.text}</text>)}          </g>          <svg className="chart-canvas" viewBox={layout.viewBox} preserveAspectRatio={layout.stretch ? 'none' : undefined} role={layout.radial ? 'presentation' : undefined} aria-hidden={layout.radial ? undefined : 'true'}>{paths}{layout.radial ? points : null}</svg>          {layout.radial ? null : points}          {layout.values.length ? <g aria-hidden="true">{layout.values.map((written, index) => <text className={written.classes} x={written.x} y={written.y} key={index}>{written.text}</text>)}</g> : null}        </svg>        {layout.center ? (          <div className="chart-center">            {layout.center.value ? <p className="chart-center-value">{layout.center.value}</p> : null}            {layout.center.label ? <p className="chart-center-label">{layout.center.label}</p> : null}          </div>        ) : null}        <div className="chart-tip" aria-hidden="true" hidden />      </div>      {!layout.legend.length ? null : layout.toggle ? (        <div className="chart-legend" role="group" aria-label={layout.legendLabel}>          {layout.legend.map(key => (            <label className={key.category ? `chart-key category-${key.category}` : 'chart-key'} key={key.name}>              <input type="checkbox" className="chart-key-input" value={key.name} defaultChecked={!key.hidden} />{entry(key)}            </label>          ))}        </div>      ) : (        <ul className="chart-legend" aria-label={layout.legendLabel}>          {layout.legend.map(key => <li className={key.category ? `chart-key category-${key.category}` : 'chart-key'} key={key.name}>{entry(key)}</li>)}        </ul>      )}    </figure>  )}
ui/Chart.svelte
<script lang="ts" module>  import type { HTMLAttributes } from 'svelte/elements'  import type { ChartConfig, ChartSeries } from '@master/ui/behaviors/chart.js'  export type { ChartConfig, ChartSeries }  export interface ChartProps extends Omit<HTMLAttributes<HTMLElement>, 'children'>, Omit<ChartConfig, 'hidden'> {    /** The names of the hidden series, as the legend's unchecked boxes say. Bind it, or leave it out: none. */    value?: string[]    onValueChange?: (value: string[]) => void  }</script><script lang="ts">  import { untrack } from 'svelte'  import { chart, chartLayout, type ChartLayout, type ChartMark } from '@master/ui/behaviors/chart.js'  import { behavior } from './behavior.svelte.js'  let { type, label, labels, series, stacked, horizontal, mark, curve, min, max, ticks, axis, format, tickFormat, xMin, xMax, xTicks, xFormat, dots, values, current, legend, toggle, legendLabel, hole, center, total, bins, ascending, words, locale, value = $bindable(), onValueChange, class: className, ...root }: ChartProps = $props()  const first = untrack(() => value ?? [])  let hidden = $state.raw(first)  const layout = $derived(chartLayout({ type, label, labels, series, stacked, horizontal, mark, curve, min, max, ticks, axis, format, tickFormat, xMin, xMax, xTicks, xFormat, dots, values, current, legend, toggle, legendLabel, hole, center, total, bins, ascending, words, locale, hidden }))  const attach = behavior(chart, () => ({ hidden: first, draw: (next: string[]) => { hidden = next } }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },  })  const classes = (item: ChartMark | ChartLayout['paths'][number]) => (item.category ? `${item.classes} category-${item.category}` : item.classes)  /** What only a mark knows, a share of its color or a bubble's size, goes on as a custom property. */  const known = (item: { tone?: number, size?: number }) => [item.tone === undefined ? '' : `--chart-tone: ${item.tone}%`, item.size === undefined ? '' : `--chart-dot: ${item.size}px`].filter(Boolean).join('; ') || undefined</script><!--  @component  A chart, in every form the chart behavior lays out, in one SVG. Svelte writes it from  `chartLayout()`, the same layout the behavior writes, so it is in the first HTML; the behavior shows the  readout of the point under the pointer or the keys, and says which series the legend hides.-->{#snippet points()}  {#each layout.points as point, at (point.index)}    <!-- The first point is the stop in the tab order of the first render; the behavior moves it from there. A form         may pass over a series, so the first point is the first written, whatever its index. -->    <!-- svelte-ignore a11y_no_noninteractive_tabindex -->    <g class="chart-point" role="listitem" aria-label={point.text} aria-current={point.current ? 'true' : undefined} data-label={point.label} tabindex={at ? -1 : 0} style="--chart-x: {point.x}; --chart-y: {point.y}; --chart-reach: {point.reach}; --chart-index: {point.index}">      {#if point.hit && 'd' in point.hit}        <path class="chart-hit" d={point.hit.d} />      {:else if point.hit && 'r' in point.hit}        <circle class="chart-hit" cx={point.hit.cx} cy={point.hit.cy} r={point.hit.r} />      {:else if point.hit}        <rect class="chart-hit" x={point.hit.x} y={point.hit.y} width={point.hit.width} height={point.hit.height} />      {/if}      {#if point.cursor}<line class="chart-cursor" x1={point.cursor.x1} y1={point.cursor.y1} x2={point.cursor.x2} y2={point.cursor.y2} />{/if}      {#each point.marks as item, at (at)}        {#if item.kind === 'bar'}          <rect class={classes(item)} x={item.x} y={item.y} width={item.width} height={item.height} style={known(item)} data-name={item.name} data-value={item.name === undefined ? undefined : item.value ?? ''} />        {:else if item.kind === 'dot'}          <circle class={classes(item)} cx={item.cx} cy={item.cy} r={item.r || undefined} style={known(item)} data-name={item.name} data-value={item.name === undefined ? undefined : item.value ?? ''} />        {:else if item.kind === 'line'}          <line class={classes(item)} x1={item.x1} y1={item.y1} x2={item.x2} y2={item.y2} data-name={item.name} data-value={item.name === undefined ? undefined : item.value ?? ''} />        {:else}          <path class={classes(item)} d={item.d} stroke-width={item.stroke || undefined} pathLength={item.kind === 'arc' ? 1 : undefined} style={known(item)} data-name={item.name} data-value={item.name === undefined ? undefined : item.value ?? ''} />        {/if}      {/each}    </g>  {/each}{/snippet}{#snippet entry(key: ChartLayout['legend'][number])}  <span class={key.mark}></span>{key.name}{#if key.value !== undefined}<span class="chart-key-value">{key.value}</span>{/if}{/snippet}<figure class={['chart', className]} {@attach attach} {...root}>  <div class="chart-body" style="--chart-gutter: {layout.gutter}; --chart-tail: {layout.tail}">    <svg class={layout.classes} role="list" aria-label={layout.label || undefined}>      <g aria-hidden="true">        {#each layout.grid as line, index (index)}<line class={['chart-grid', line.base && 'chart-grid-base']} x1={line.x1} y1={line.y1} x2={line.x2} y2={line.y2} />{/each}        {#each layout.ticks as tick, index (index)}<text class={tick.classes} x={tick.x} y={tick.y} style={tick.at ? `--chart-x: ${tick.at[0]}; --chart-y: ${tick.at[1]}` : undefined}>{tick.text}</text>{/each}      </g>      <svg class="chart-canvas" viewBox={layout.viewBox} preserveAspectRatio={layout.stretch ? 'none' : undefined} role={layout.radial ? 'presentation' : undefined} aria-hidden={layout.radial ? undefined : 'true'}>        {#each layout.paths as path, index (index)}<path class={classes(path)} d={path.d} style={known(path)} />{/each}        {#if layout.radial}{@render points()}{/if}      </svg>      {#if !layout.radial}{@render points()}{/if}      {#if layout.values.length}        <g aria-hidden="true">          {#each layout.values as written, index (index)}<text class={written.classes} x={written.x} y={written.y}>{written.text}</text>{/each}        </g>      {/if}    </svg>    {#if layout.center}      <div class="chart-center">        {#if layout.center.value}<p class="chart-center-value">{layout.center.value}</p>{/if}        {#if layout.center.label}<p class="chart-center-label">{layout.center.label}</p>{/if}      </div>    {/if}    <div class="chart-tip" aria-hidden="true" hidden></div>  </div>  {#if layout.legend.length && layout.toggle}    <div class="chart-legend" role="group" aria-label={layout.legendLabel}>      {#each layout.legend as key (key.name)}        <label class={['chart-key', key.category && `category-${key.category}`]}><input type="checkbox" class="chart-key-input" value={key.name} checked={!key.hidden} />{@render entry(key)}</label>      {/each}    </div>  {:else if layout.legend.length}    <ul class="chart-legend" aria-label={layout.legendLabel}>      {#each layout.legend as key (key.name)}<li class={['chart-key', key.category && `category-${key.category}`]}>{@render entry(key)}</li>{/each}    </ul>  {/if}</figure>
ui/Chart.vue
<script lang="ts">import type { ChartConfig, ChartSeries } from '@master/ui/behaviors/chart.js'export type { ChartConfig, ChartSeries }</script><script setup lang="ts">import { computed, shallowRef, useTemplateRef } from 'vue'import { chart, chartLayout, type ChartLayout, type ChartMark, type ChartType } from '@master/ui/behaviors/chart.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })// A legend, its checkboxes and the scale's figures are the chart's to decide when they are left out: absent is not false.const { type, label, labels, series, stacked, horizontal, mark, curve, min, max, ticks, axis = undefined, format, tickFormat, xMin, xMax, xTicks, xFormat, dots, values, current, legend = undefined, toggle = undefined, legendLabel, hole, center, total, bins, ascending, words, locale } = defineProps<{  /** `bar` by default. */  type?: ChartType  /** What the chart shows and in what unit: the plot's accessible name. */  label?: string  /** The names along the scale, around a radar or of a heatmap's columns. */  labels?: string[]  series?: ChartSeries[]  /** Bars, or areas, stand on each other instead of side by side. `percent` makes every stack a whole; `stream` centers stacked areas on a middle line. */  stacked?: boolean | 'percent' | 'stream'  /** Bars, ranges, dumbbells and boxes run across, one row to a label. */  horizontal?: boolean  /** How a bar is drawn: `lollipop` is a stem with a dot at its end. */  mark?: 'bar' | 'lollipop'  /** How a line goes from point to point. `smooth` never overshoots a value. */  curve?: 'smooth' | 'linear' | 'step'  /** Where the scale starts and ends. 0, or the lowest value below it, to a round number above the highest by default. */  min?: number  max?: number  /** About how many steps the scale is marked in. 4 by default. */  ticks?: number  /** Whether the scale's figures are written. False leaves its hairlines alone. */  axis?: boolean  /** How a value is written beside its name. */  format?: (value: number) => string  /** How a tick is written. Compact once the scale reaches 10,000 by default. */  tickFormat?: (value: number) => string  /** A scatter's scale across, as `min`, `max`, `ticks` and `tickFormat`. */  xMin?: number  xMax?: number  xTicks?: number  xFormat?: (value: number) => string  /** A line's points are always marked, not only the one under the pointer. */  dots?: boolean  /** Every bar's value is written at its end. */  values?: boolean  /** The index of the point that is the point of the chart: it is marked `aria-current`. */  current?: number  /** Whether a legend is written. With two series or more by default. */  legend?: boolean  /** Whether the legend's entries are checkboxes that show and hide a series. True by default. */  toggle?: boolean  /** The legend's accessible name. `Series` by default. */  legendLabel?: string  /** A donut's hole, as a share of its radius. .7 by default. */  hole?: number  /** What stands in a donut's hole or within rings. */  center?: { value: string, label?: string }  /** A waterfall's closing bar: its name. Without one the chart ends on its last step. */  total?: string  /** About how many bins a histogram sorts its readings into. Chosen from their count by default. */  bins?: number  /** In a bump chart, the lowest value ranks first. */  ascending?: boolean  /** The names of a box plot's five figures, in the page's language. */  words?: { min?: string, q1?: string, median?: string, q3?: string, max?: string }  /** A BCP 47 tag for the numbers. `en-US` by default. */  locale?: string}>()/** The names of the hidden series, as the legend's unchecked boxes say: `v-model`. None by default. */const model = defineModel<string[]>()/* * A chart, in every form the chart behavior lays out, in one SVG. Vue writes it from * `chartLayout()`, the same layout the behavior writes, so it is in the first HTML; the behavior shows the * readout of the point under the pointer or the keys, and says which series the legend hides. * * The points are written in one of two places: in the canvas where the layout is `radial`, on the plot otherwise. The * first written, whatever its index, is the stop in the tab order of the first render; the behavior moves it from * there. */const first = model.value ?? []const hidden = shallowRef<string[]>(first)const layout = computed(() => chartLayout({ type, label, labels, series, stacked, horizontal, mark, curve, min, max, ticks, axis, format, tickFormat, xMin, xMax, xTicks, xFormat, dots, values, current, legend, toggle, legendLabel, hole, center, total, bins, ascending, words, locale, hidden: hidden.value }))const root = useTemplateRef<HTMLElement>('root')useBehavior(root, chart, () => ({ hidden: first, draw: (next: string[]) => { hidden.value = next } }), model)const classes = (item: ChartMark | ChartLayout['paths'][number]) => (item.category ? `${item.classes} category-${item.category}` : item.classes)const named = (item: ChartMark) => (item.name === undefined ? undefined : item.value ?? '')/** What only a mark knows, a share of its color or a bubble's size, goes on as a custom property; any other mark has no style. */const known = (item: { tone?: number, size?: number }) => {  const style = [item.tone === undefined ? '' : `--chart-tone: ${item.tone}%`, item.size === undefined ? '' : `--chart-dot: ${item.size}px`].filter(Boolean).join('; ')  return style ? { style } : undefined}/** A name around a radar is moved to its place in the square; any other tick has no style. */const place = (at: [number, number] | null) => (at ? { style: `--chart-x: ${at[0]}; --chart-y: ${at[1]}` } : undefined)</script><template>  <figure class="chart" ref="root" v-bind="$attrs">    <div class="chart-body" :style="`--chart-gutter: ${layout.gutter}; --chart-tail: ${layout.tail}`">      <svg :class="layout.classes" role="list" :aria-label="layout.label || undefined">        <g aria-hidden="true">          <line v-for="(line, index) in layout.grid" :key="index" class="chart-grid" :class="{ 'chart-grid-base': line.base }" :x1="line.x1" :y1="line.y1" :x2="line.x2" :y2="line.y2" />          <text v-for="(tick, index) in layout.ticks" :key="index" :class="tick.classes" :x="tick.x" :y="tick.y" v-bind="place(tick.at)">{{ tick.text }}</text>        </g>        <svg class="chart-canvas" :viewBox="layout.viewBox" :preserveAspectRatio="layout.stretch ? 'none' : undefined" :role="layout.radial ? 'presentation' : undefined" :aria-hidden="layout.radial ? undefined : 'true'">          <path v-for="(path, index) in layout.paths" :key="index" :class="classes(path)" :d="path.d" v-bind="known(path)" />          <template v-if="layout.radial">            <g v-for="(point, position) in layout.points" :key="point.index" class="chart-point" role="listitem" :aria-label="point.text" :aria-current="point.current ? 'true' : undefined" :data-label="point.label" :tabindex="position ? -1 : 0" :style="`--chart-x: ${point.x}; --chart-y: ${point.y}; --chart-reach: ${point.reach}; --chart-index: ${point.index}`">              <path v-if="point.hit && 'd' in point.hit" class="chart-hit" :d="point.hit.d" />              <circle v-else-if="point.hit && 'r' in point.hit" class="chart-hit" :cx="point.hit.cx" :cy="point.hit.cy" :r="point.hit.r" />              <rect v-else-if="point.hit" class="chart-hit" :x="point.hit.x" :y="point.hit.y" :width="point.hit.width" :height="point.hit.height" />              <line v-if="point.cursor" class="chart-cursor" :x1="point.cursor.x1" :y1="point.cursor.y1" :x2="point.cursor.x2" :y2="point.cursor.y2" />              <template v-for="(item, at) in point.marks" :key="at">                <rect v-if="item.kind === 'bar'" :class="classes(item)" :x="item.x" :y="item.y" :width="item.width" :height="item.height" v-bind="known(item)" :data-name="item.name" :data-value="named(item)" />                <circle v-else-if="item.kind === 'dot'" :class="classes(item)" :cx="item.cx" :cy="item.cy" :r="item.r || undefined" v-bind="known(item)" :data-name="item.name" :data-value="named(item)" />                <line v-else-if="item.kind === 'line'" :class="classes(item)" :x1="item.x1" :y1="item.y1" :x2="item.x2" :y2="item.y2" :data-name="item.name" :data-value="named(item)" />                <path v-else :class="classes(item)" :d="item.d" :stroke-width="item.stroke || undefined" :pathLength="item.kind === 'arc' ? 1 : undefined" v-bind="known(item)" :data-name="item.name" :data-value="named(item)" />              </template>            </g>          </template>        </svg>        <template v-if="!layout.radial">          <g v-for="(point, position) in layout.points" :key="point.index" class="chart-point" role="listitem" :aria-label="point.text" :aria-current="point.current ? 'true' : undefined" :data-label="point.label" :tabindex="position ? -1 : 0" :style="`--chart-x: ${point.x}; --chart-y: ${point.y}; --chart-reach: ${point.reach}; --chart-index: ${point.index}`">            <path v-if="point.hit && 'd' in point.hit" class="chart-hit" :d="point.hit.d" />            <circle v-else-if="point.hit && 'r' in point.hit" class="chart-hit" :cx="point.hit.cx" :cy="point.hit.cy" :r="point.hit.r" />            <rect v-else-if="point.hit" class="chart-hit" :x="point.hit.x" :y="point.hit.y" :width="point.hit.width" :height="point.hit.height" />            <line v-if="point.cursor" class="chart-cursor" :x1="point.cursor.x1" :y1="point.cursor.y1" :x2="point.cursor.x2" :y2="point.cursor.y2" />            <template v-for="(item, at) in point.marks" :key="at">              <rect v-if="item.kind === 'bar'" :class="classes(item)" :x="item.x" :y="item.y" :width="item.width" :height="item.height" v-bind="known(item)" :data-name="item.name" :data-value="named(item)" />              <circle v-else-if="item.kind === 'dot'" :class="classes(item)" :cx="item.cx" :cy="item.cy" :r="item.r || undefined" v-bind="known(item)" :data-name="item.name" :data-value="named(item)" />              <line v-else-if="item.kind === 'line'" :class="classes(item)" :x1="item.x1" :y1="item.y1" :x2="item.x2" :y2="item.y2" :data-name="item.name" :data-value="named(item)" />              <path v-else :class="classes(item)" :d="item.d" :stroke-width="item.stroke || undefined" :pathLength="item.kind === 'arc' ? 1 : undefined" v-bind="known(item)" :data-name="item.name" :data-value="named(item)" />            </template>          </g>        </template>        <g v-if="layout.values.length" aria-hidden="true">          <text v-for="(written, index) in layout.values" :key="index" :class="written.classes" :x="written.x" :y="written.y">{{ written.text }}</text>        </g>      </svg>      <div v-if="layout.center" class="chart-center">        <p v-if="layout.center.value" class="chart-center-value">{{ layout.center.value }}</p>        <p v-if="layout.center.label" class="chart-center-label">{{ layout.center.label }}</p>      </div>      <div class="chart-tip" aria-hidden="true" hidden></div>    </div>    <div v-if="layout.legend.length && layout.toggle" class="chart-legend" role="group" :aria-label="layout.legendLabel">      <label v-for="key in layout.legend" :key="key.name" class="chart-key" :class="key.category && `category-${key.category}`"><input type="checkbox" class="chart-key-input" :value="key.name" :checked="!key.hidden" /><span :class="key.mark"></span>{{ key.name }}<span v-if="key.value !== undefined" class="chart-key-value">{{ key.value }}</span></label>    </div>    <ul v-else-if="layout.legend.length" class="chart-legend" :aria-label="layout.legendLabel">      <li v-for="key in layout.legend" :key="key.name" class="chart-key" :class="key.category && `category-${key.category}`"><span :class="key.mark"></span>{{ key.name }}<span v-if="key.value !== undefined" class="chart-key-value">{{ key.value }}</span></li>    </ul>  </figure></template>

若複製的元件只繪製折線圖、面積圖或長條圖,可將原本從 chart.js 的匯入改成圖表核心與 Cartesian 圖形。所需型別同樣從 chart-core.js 匯入,並在模組層級註冊圖形。

import { chartCore as chart, chartForms, chartLayout } from '@master/ui/behaviors/chart-core.js'import { chartCartesian } from '@master/ui/behaviors/chart-cartesian.js'chartForms(chartCartesian)

匯入別名讓複製的元件沿用原本的行為掛載。伺服器用 chartLayout() 繪製,掛載後可用方向鍵在資料點間移動,並用 Escape 關閉讀值提示。

#類別

類別說明
chart圖表本身:先是繪圖區主體,下方接著圖例
chart-quiet長條為淡色,標有 aria-current 的資料點為墨色搭配 chart 使用
chart-split圖例排成一欄名稱與數字,立在繪圖區旁;空間不足時移到繪圖區下方搭配 chart 使用
chart-body繪圖區所在的位置:數值提示以它為基準定位,--chart-gutter 則在旁邊為刻度數字保留空間
chart-plotSVG 本身,寬度與所在空間相同,高度為 --chart-height。請為它設定 role="list",並提供說明呈現內容及單位的名稱。
chart-plot-radial圓餅圖、圓環圖、環形進度圖、旭日圖或華夫格圖皆採正方形,邊長為 --chart-size。搭配 chart-plot 使用
chart-plot-radar雷達圖:位於繪圖區中央的正方形,旁邊留有空間放置環繞它的名稱搭配 chart-plot 使用
chart-canvas巢狀 SVG 路徑可寫在兩種座標框內。一般圖表使用 100 × 100 的座標框,透過 preserveAspectRatio="none" 拉伸至整個繪圖區。放射狀圖表使用以 0 為中心且維持原比例的座標框。若某種圖表以路徑呈現資料點,這些路徑也放在該座標框內。
chart-grid刻度的細線,以百分比定位
chart-grid-base基線:比其他細線明顯一階搭配 chart-grid 使用
chart-tick刻度數字,或沿著刻度排列的名稱
chart-tick-y位於繪圖區旁,對齊所屬的細線搭配 chart-tick 使用
chart-tick-x位於繪圖區下方,以所在位置為中心搭配 chart-tick 使用
chart-tick-around環繞雷達圖:從繪圖區中央移到其正方形中 --chart-x 和 --chart-y 所指的位置搭配 chart-tick 使用
chart-tick-start從所在位置開始,而非以該位置為中心:用於從一側延伸到另一側的折線的第一個名稱搭配 chart-tick 使用
chart-tick-end結束於所在位置搭配 chart-tick 使用
chart-tick-scale雷達圖的刻度數字:字級較小,位於第一條輻線旁搭配 chart-tick 使用
chart-tick-minor繪圖區窄於 24rem 時會省略的名稱搭配 chart-tick 使用
chart-line以折線呈現的序列;無論畫布伸展多寬,線寬都是 --chart-stroke
chart-area折線下方的面積:一層向下漸淡的同色淡色底
chart-area-stacked堆疊面積中的一層:會遮住下層的淡色搭配 chart-area 使用
chart-point單一刻度位置、扇形、圓環、矩形區塊、斜率圖的資料序列或圓點,以及其對應的標記。請設定 role="listitem" 並提供說明其數值的無障礙名稱。數值提示會使用此項目的 --chart-x、--chart-y 和 --chart-reach。
chart-hit指標的感應範圍大於圖形本身時所用的區域:刻度上一格的整個範圍、圓點周圍的空間,或雷達圖的楔形區域。焦點外框會畫在它上面。
chart-hit-line沿著線條加上一道較寬的透明筆畫,擴大指標可命中的範圍。搭配 chart-hit 使用
chart-cursor穿過資料點的細線,在指標移到該資料點或該資料點取得焦點時顯示
chart-bar以百分比定位的長條,遠離基線的一端為圓角
chart-bar-inner在堆疊中位於另一根長條之下:方角,並與下一根長條相隔 --chart-gap 的間隙搭配 chart-bar 使用
chart-bar-down小於零的數值:圓角位於下端;在橫向長條中,則位於起始端搭配 chart-bar 使用
chart-bar-across橫向延伸的長條,圓角位於遠端搭配 chart-bar 使用
chart-bar-floating長條橫跨兩個數值,兩端皆不以基線為起點,且兩端均為圓角。搭配 chart-bar 使用
chart-bar-bin直方圖中代表各組區間的長條彼此相接,只用一條與背景同色的細線分隔。搭配 chart-bar 使用
chart-bar-rise瀑布圖的上升階使用成功色。搭配 chart-bar 使用
chart-bar-fall瀑布圖的下降階使用危險色。搭配 chart-bar 使用
chart-dot折線圖、雷達圖或散佈圖的資料點,以所屬顏色的圓點呈現,外圍加上一圈與背景同色的描邊。
chart-dot-quiet只在指標移到所屬資料點或該資料點取得焦點時顯示搭配 chart-dot 使用
chart-dot-bubble氣泡以所屬顏色描邊,內部填上同色的淡色,大小由該氣泡上的 --chart-dot 決定。搭配 chart-dot 使用
chart-dot-outlier盒鬚圖中遠離其他數值的離群值,以小型空心標記呈現。搭配 chart-dot 使用
chart-value繪圖區上的文字標記,包括長條末端的數值、折線最後一個資料點旁的名稱,以及矩形區塊的名稱
chart-value-across位於橫向長條的末端之後搭配 chart-value 使用
chart-value-before位於繪圖區前方,延伸至繪圖區邊緣搭配 chart-value 使用
chart-value-tile從矩形區塊的起始角顯示區塊名稱搭配 chart-value 使用
chart-value-quiet在矩形區塊名稱下方顯示數值,降低視覺強調搭配 chart-value 使用
chart-slice圓餅圖或圓環圖的一個扇形
chart-track圓環的軌道:代表數值所對照的整體,使用所屬顏色的淡色
chart-arc圓環的數值,從頂端開始,兩端為圓頭。請為它設定 pathLength="1",讓它在首次出現時逐漸填滿。
chart-web雷達圖的網格:每個刻度標記各有一圈,每個名稱各有一條輻線
chart-shape雷達圖的序列:輪廓線加上同色的淡色底
chart-band折線數值的可能範圍,以介於上下限之間的帶狀區域呈現
chart-stem棒棒糖圖中從基準線連到圓點的線段,以及啞鈴圖中連接兩端的線段
chart-whisker從數值的可能下限延伸至上限,穿過長條末端或盒鬚圖的盒體
chart-box盒鬚圖的盒體,從第一四分位數延伸至第三四分位數
chart-median中位數以一條與背景同色的線穿過盒體來標示
chart-link瀑布圖中從一根長條末端連到下一根長條的細線
chart-knot斜率圖或排名變化圖的資料點,以長度為零的圓端路徑繪製,在畫布拉伸時仍保持圓形
chart-cell熱圖儲存格的色彩強度由 --chart-tone 決定
chart-unit華夫格圖的每一格代表整體的 1%
chart-stage漏斗圖各階段的色調比前一階段淺一級
chart-tile樹狀矩形圖的矩形區塊採用淡色填滿,並在區塊內顯示名稱。
chart-center圓環圖中央或環形進度圖內側顯示的內容
chart-center-value中央的數字
chart-center-label該數字所計量的項目
chart-tip指標所在資料點旁的數值提示,在行為填入內容前保持隱藏
chart-tip-title資料點的名稱
chart-tip-row數值提示中對應單一資料序列的項目,會套用該序列的色彩類別 class。
chart-tip-key一道序列顏色的短線
chart-tip-name序列的名稱
chart-tip-value序列在該資料點的數值
chart-legend各序列的名稱,旁邊各有一個所屬顏色的標示
chart-key圖例中的一個項目,會套用該資料序列的色彩類別 class。透過 label 包住的核取方塊,可切換序列的顯示與隱藏。
chart-key-input項目的核取方塊:畫面上看不見,但仍在 Tab 順序中,序列顯示時為勾選狀態
chart-key-mark項目的標示:一個小方塊,對應長條、面積或扇形的外觀
chart-key-line一道短線,對應折線的外觀搭配 chart-key-mark 使用
chart-key-dot一個圓點,對應散佈圖資料點的外觀搭配 chart-key-mark 使用
chart-key-value名稱之後的數字:扇形的占比,或圓環的數值

#自訂屬性

屬性預設值說明
--chart-height14rem繪圖區的高度;雷達圖的正方形不會高過此值
--chart-size12rem圓餅圖、圓環圖、環形進度圖、旭日圖或華夫格圖的寬度
--chart-colorvar(--color-surface-inverse)未指定色彩類別的標記所用的前景色
--chart-stroke2px折線及雷達圖輪廓線的寬度
--chart-dot4px圓點的半徑。氣泡則使用各自的半徑
--chart-bar-radius.25rem長條圓角的半徑
--chart-gap2px堆疊中各長條之間的間隙
--chart-surfacevar(--surface-color, var(--color-surface-base))圖表背景色,用於混合圓點外圈的顏色與標記的淡色
--chart-gutter繪圖區旁的數字占幾位數的寬度;0 表示不保留空間設定於 chart-body
--chart-tail繪圖區後方的標籤寬度,以數字字元數為單位。適用於橫條末端的數值和斜率圖線段末端的名稱設定於 chart-body
--chart-x數值提示在繪圖區橫向上的位置,介於 0 到 1;資料點帶有自己的值,供行為轉交給數值提示,環繞雷達圖的名稱則用它表示自己在正方形中的位置設定於 chart-tip
--chart-y數值提示在繪圖區縱向上的位置,從頂端的 0 到 1設定於 chart-tip
--chart-reach資料點的圖形距離數值提示的位置多遠,以占繪圖區的比例表示,讓數值提示能避開這些圖形:指左右兩側的距離,在橫向長條中則為上下的距離設定於 chart-tip
--chart-tone方格、漏斗圖階段或外環扇形在混色時採用所屬顏色的比例,以百分比表示,預設為 100%。設定於 chart-cell
--chart-index資料點的順序,用來錯開各標記的繪製動畫。設定於 chart-point

#原始碼

@master/ui/components/chart.css
/* * Chart: numbers drawn in one SVG, in every form the chart behavior lays out: lines, areas and bars, a scatter, * a pie and a donut, rings, a radar, a waterfall, ranges, a slope, a bump, a marimekko, a histogram, a box plot, * a heatmap, a funnel, a waffle, a treemap and a sunburst. * The plot is an SVG with no box of its own units: it is as wide as the room it is given and --chart-height * tall, and everything that stands on a scale (a hairline, a tick, a bar, a dot) is placed by percentages of it. * Only what must be a path (a line, an area, a slice) is drawn in chart-canvas, a 100 by 100 box inside the plot * that stretches to it, with strokes that keep their width however far it stretches. So one drawing fits any * width, nothing is measured, and text is never scaled. A pie, a donut and rings are square, --chart-size wide. * * A chart of one series is ink, as a progress bar fills with ink. Several series, and the parts of a whole, are * told apart by category: a mark with a category-<name> class takes that category's mark color, and its name * stands in the legend. The scale is hairlines with the baseline one step firmer, and its figures are muted. * Bars turn their corners at the end away from the baseline, and stacked bars are parted by a gap of * --chart-gap. A line is --chart-stroke wide; the area under it fades out downward. * * Each step of the scale, each slice and each dot is a chart-point: a list item that says its values in words. * Under the pointer, or with the focus, a point shows the hairline through it and its dots, and the bars and * slices of the other points step back to a tint, at once. chart-tip is the readout beside the point: it stands * at --chart-x and --chart-y of the plot, on the side with more room, and never leaves the plot. * In a chart-quiet chart every bar is a tint and the point marked aria-current is ink. * * Marks that are steps of one color (a heatmap's cells, a funnel's stages, the outer ring of a sunburst) take * --chart-tone of it. A waterfall's steps up and down are the two status inks, beside the sign of their value. * * Marks draw themselves in when they first appear: bars rise from the baseline, lines run in from the start, * slices and shapes open from the center, a ring fills. Reduced motion removes all of it. * The area's fade is a mask and the bars' corners a clip; a browser without either on an SVG shape shows an even * tint and square bars. Labels thin out in a narrow plot with a container query, and stay without one. */@layer components.ui {  .chart {    --chart-height: 14rem;    --chart-size: 12rem;    --chart-color: var(--color-surface-inverse);    --chart-stroke: 2px;    --chart-dot: 4px;    --chart-bar-radius: .25rem;    --chart-gap: 2px;    /* The surface the chart stands on, which a card or a sheet publishes: gaps and the rings around dots are cut from it. */    --chart-surface: var(--surface-color, var(--color-surface-base));    display: grid;    grid-template-columns: minmax(0, 1fr);    gap: .875rem;    min-width: 0;    margin: 0;    padding: 0;    color: var(--color-text-muted);    font: 400 .71875rem/1.4 var(--font-family-sans);    font-feature-settings: inherit;    font-variant-numeric: tabular-nums;    /* Split: the legend stands beside the plot as a column of names and figures, and goes under it when there is no room. */    &.chart-split {      display: flex;      flex-wrap: wrap;      align-items: center;      gap: 1rem 1.75rem;      .chart-body {        flex: 1 1 14rem;      }      .chart-body:has(.chart-plot-radial) {        flex: none;      }      .chart-legend {        flex: 1 1 9rem;        flex-direction: column;        gap: .125rem;      }      .chart-key-value {        margin-inline-start: auto;        padding-inline-start: 1rem;      }    }    /* Quiet: bars are a tint, and the point marked aria-current is the ink. For a period in which one day matters. */    &.chart-quiet {      .chart-point:not([aria-current='true']) .chart-bar {        fill: color-mix(in oklab, var(--chart-bar-color) 16%, var(--chart-surface));      }      @media (hover: hover) {        .chart-point:not([aria-current='true']):hover .chart-bar {          fill: color-mix(in oklab, var(--chart-bar-color) 36%, var(--chart-surface));        }      }      .chart-point:not([aria-current='true']):focus .chart-bar {        fill: color-mix(in oklab, var(--chart-bar-color) 36%, var(--chart-surface));      }      /* In forced colors the current point is the system's highlight, as a gantt's and a schedule's current mark is. */      @media (forced-colors: active) {        .chart-point[aria-current='true'] .chart-bar {          fill: Highlight;        }      }    }    @media (forced-colors: active) {      --chart-color: CanvasText;      --chart-surface: Canvas;    }  }  /*   * The plot's place: the tip is placed against it, and the figures of the scale stand in the room beside and   * under it, --chart-gutter digits wide. It is the container the labels' thinning asks about.   */  .chart-body {    position: relative;    container-type: inline-size;    min-width: 0;    /* The plot runs from the left in every language, so its gutter and its tail are left and right. */    margin-left: calc(var(--chart-gutter, 0) * 1ch + min(var(--chart-gutter, 0), 1) * .625rem);    margin-right: calc(var(--chart-tail, 0) * 1ch + min(var(--chart-tail, 0), 1) * .625rem);    &:has(.chart-tick-x) {      margin-bottom: 1.375rem;    }    /* Values written over the bars need a line above the plot; those written beside or on a mark do not. */    &:has(.chart-value) {      margin-top: 1rem;    }    &:has(.chart-value-across), &:has(.chart-value-before), &:has(.chart-value-tile) {      margin-top: 0;    }    /* A pie, a donut and rings: a square, as wide as --chart-size and no wider than its room. */    &:has(.chart-plot-radial) {      container-type: normal;      width: var(--chart-size);      max-width: 100%;      margin-inline: auto;    }    /* A radar: a square in the middle of the plot, with room beside it for the names around it. */    &:has(.chart-plot-radar) {      --chart-side: min(var(--chart-height), 100cqi - 9rem);      margin-block: .75rem;    }  }  .chart-plot {    display: block;    width: 100%;    height: var(--chart-height);    overflow: visible;    /* The scale runs from the left in every language, so a label's anchor means the same side. */    direction: ltr;    /* A finger moves along the points; the page still scrolls the other way. */    touch-action: pan-y;    user-select: none;    -webkit-user-select: none;    /* A point a finger focuses is marked on its marks: the browser's tap flash would cover its whole box. */    -webkit-tap-highlight-color: transparent;    &.chart-plot-radial {      height: auto;      aspect-ratio: 1;      touch-action: auto;    }    &.chart-plot-radar {      height: var(--chart-side);      touch-action: auto;    }    /* Under the pointer or with the focus, the bars and slices of the other points step back to a tint, at once. */    @media (hover: hover) {      &:has(.chart-point:hover) .chart-point:not(:hover) {        .chart-bar {          fill: color-mix(in oklab, var(--chart-bar-color) 30%, var(--chart-surface));        }        .chart-slice, .chart-arc, .chart-line, .chart-knot, .chart-unit, .chart-stage, .chart-box, .chart-stem {          opacity: .32;        }      }    }    &:has(.chart-point:focus) .chart-point:not(:focus) {      .chart-bar {        fill: color-mix(in oklab, var(--chart-bar-color) 30%, var(--chart-surface));      }      .chart-slice, .chart-arc, .chart-line, .chart-knot, .chart-unit, .chart-stage, .chart-box, .chart-stem {        opacity: .32;      }    }  }  /* The box paths are written in: it stretches to the plot, or keeps its shape in a radial chart. */  .chart-canvas {    overflow: visible;  }  /* The scale: a hairline at each tick. The baseline is one step firmer. */  .chart-grid {    stroke: var(--color-line-hair);    stroke-width: 1px;    shape-rendering: crispEdges;    &.chart-grid-base {      stroke: var(--color-line-divider);    }    @media (forced-colors: active) {      stroke: GrayText;    }  }  /* A figure of the scale or a name along it, placed on its hairline and moved into the room beside the plot. */  .chart-tick {    fill: currentColor;    stroke: none;    &.chart-tick-y {      text-anchor: end;      dominant-baseline: central;      transform: translate(-.625rem, 0);    }    &.chart-tick-x {      text-anchor: middle;      transform: translate(0, 1.25rem);    }    /* Around a radar: moved from the middle of the plot to its place in the square. */    &.chart-tick-around {      text-anchor: middle;      dominant-baseline: central;      fill: var(--color-text-body);      transform: translate(calc((var(--chart-x) - .5) * var(--chart-side)), calc((var(--chart-y) - .5) * var(--chart-side)));    }    &.chart-tick-start {      text-anchor: start;    }    &.chart-tick-end {      text-anchor: end;    }    /* A figure of a radar's scale: small, beside the first spoke, in the room between two rings. */    &.chart-tick-scale {      text-anchor: start;      dominant-baseline: auto;      fill: currentColor;      font-size: .625rem;      transform: translate(calc((var(--chart-x) - .5) * var(--chart-side) + .25rem), calc((var(--chart-y) - .5) * var(--chart-side) - .1875rem));    }    /* Every other name gives way when the plot is narrow, and a small radar keeps only its names. */    @container (width < 24rem) {      &.chart-tick-minor, &.chart-tick-scale {        display: none;      }    }    /* A fill named from a token is an author color: the names around a radar take the system's text. */    @media (forced-colors: active) {      &.chart-tick-around {        fill: CanvasText;      }    }  }  /* A line: one series from point to point. */  .chart-line {    fill: none;    stroke: var(--category-mark, var(--chart-color));    stroke-width: var(--chart-stroke);    stroke-linecap: round;    stroke-linejoin: round;    vector-effect: non-scaling-stroke;    /* It runs in from the start; the clip stays a little outside the line so its round ends are whole. */    clip-path: inset(-12% -4% -12% -4%);    transition: clip-path 720ms var(--easing-glide);    @starting-style {      clip-path: inset(-12% 100% -12% -4%);    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* The area under a line: a wash of its color that fades out downward. */  .chart-area {    /* A wash of a category's color; ink, which is far darker, is thinned first so its wash is as quiet. */    fill: color-mix(in oklab, var(--category-mark, color-mix(in oklab, var(--chart-color) 55%, transparent)) 22%, transparent);    stroke: none;    mask-image: linear-gradient(to bottom, black, transparent);    transition: opacity 720ms var(--easing-glide);    @starting-style {      opacity: 0;    }    /* Stacked: each layer is a tint of its own that hides the one under it. */    &.chart-area-stacked {      fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) 26%, var(--chart-surface));      mask-image: none;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /*   * One step of the scale, one slice, one ring or one dot, with its marks: a list item that says its values.   * It takes the focus from the keys, and what marks it then is drawn on its marks, not around its box.   */  .chart-point {    outline: none;    @media (hover: hover) {      &:hover {        .chart-cursor, .chart-dot {          opacity: 1;        }      }    }    &:focus {      .chart-cursor, .chart-dot {        opacity: 1;      }    }    &:focus-visible {      .chart-hit {        stroke: var(--color-focus);      }      .chart-slice, .chart-track, .chart-stage {        stroke: var(--color-focus);        stroke-width: 2px;      }      /* A mark cut by a clip takes the ring in place of the cut, so the ring is whole. */      .chart-cell, .chart-unit, .chart-tile {        stroke: var(--color-focus);        stroke-width: 2px;        clip-path: none;      }      /* A line's ring is a band of the focus color along it. */      .chart-hit-line {        stroke: color-mix(in oklab, var(--color-focus) 24%, transparent);      }    }    /*     * Every ring a point draws is the system's highlight, and along a line it stays a band of it, as it is     * without forced colors, so the line under it still shows.     */    @media (forced-colors: active) {      &:focus-visible {        .chart-hit, .chart-slice, .chart-track, .chart-stage, .chart-cell, .chart-unit, .chart-tile {          stroke: Highlight;        }        .chart-hit-line {          stroke: color-mix(in oklab, Highlight 24%, transparent);        }      }    }  }  /* What the pointer lands on: the whole band of a step, the room around a dot, a radar's wedge. The focus ring is drawn on it. */  .chart-hit {    fill: transparent;    stroke: transparent;    stroke-width: 2px;    vector-effect: non-scaling-stroke;    rx: var(--chart-bar-radius);    pointer-events: all;    /* Along a line: a wide stroke nobody sees, so the pointer does not have to find a line two pixels wide. */    &.chart-hit-line {      fill: none;      stroke-width: 18px;      stroke-linecap: round;      stroke-linejoin: round;      pointer-events: stroke;    }  }  /* The hairline through the point under the pointer. */  .chart-cursor {    stroke: var(--color-line-mark);    stroke-width: 1px;    shape-rendering: crispEdges;    opacity: 0;    pointer-events: none;    /* A hairline named from a token: in forced colors it is the system's gray, as the grid is. */    @media (forced-colors: active) {      stroke: GrayText;    }  }  /*   * A bar. Its corners turn at the end away from the baseline, cut with a clip so the radius is true at any   * width, and it rises from the baseline when it first appears, each a moment after the one before it.   */  .chart-bar {    --chart-bar-color: var(--category-mark, var(--chart-color));    fill: var(--chart-bar-color);    stroke: none;    clip-path: inset(0 round var(--chart-bar-radius) var(--chart-bar-radius) 0 0);    transition: clip-path 560ms var(--easing-glide) calc(min(var(--chart-index, 0), 30) * 14ms);    @starting-style {      clip-path: inset(100% 0 0 0 round var(--chart-bar-radius) var(--chart-bar-radius) 0 0);    }    /* Under another bar of its stack: square, with the gap above it. */    &.chart-bar-inner {      clip-path: inset(var(--chart-gap) 0 0 0);      @starting-style {        clip-path: inset(100% 0 0 0);      }    }    /* A value under zero: it hangs from the baseline. */    &.chart-bar-down {      clip-path: inset(0 round 0 0 var(--chart-bar-radius) var(--chart-bar-radius));      @starting-style {        clip-path: inset(0 0 100% 0 round 0 0 var(--chart-bar-radius) var(--chart-bar-radius));      }    }    &.chart-bar-down.chart-bar-inner {      clip-path: inset(0 0 var(--chart-gap) 0);      @starting-style {        clip-path: inset(0 0 100% 0);      }    }    /* Across: a row of a ranking, turned at its far end. */    &.chart-bar-across {      clip-path: inset(0 round 0 var(--chart-bar-radius) var(--chart-bar-radius) 0);      @starting-style {        clip-path: inset(0 100% 0 0 round 0 var(--chart-bar-radius) var(--chart-bar-radius) 0);      }    }    &.chart-bar-across.chart-bar-inner {      clip-path: inset(0 var(--chart-gap) 0 0);      @starting-style {        clip-path: inset(0 100% 0 0);      }    }    &.chart-bar-across.chart-bar-down {      clip-path: inset(0 round var(--chart-bar-radius) 0 0 var(--chart-bar-radius));      @starting-style {        clip-path: inset(0 0 0 100% round var(--chart-bar-radius) 0 0 var(--chart-bar-radius));      }    }    &.chart-bar-across.chart-bar-down.chart-bar-inner {      clip-path: inset(0 0 0 var(--chart-gap));      @starting-style {        clip-path: inset(0 0 0 100%);      }    }    /* Between two values, with no end on the baseline: both ends are turned, and it opens from its middle. */    &.chart-bar-floating {      clip-path: inset(0 round var(--chart-bar-radius));      @starting-style {        clip-path: inset(50% round var(--chart-bar-radius));      }    }    /* A histogram's bin: it meets the bins beside it, parted by a hairline of the surface. */    &.chart-bar-bin {      clip-path: inset(0 .5px 0 .5px round var(--chart-bar-radius) var(--chart-bar-radius) 0 0);      @starting-style {        clip-path: inset(100% .5px 0 .5px round var(--chart-bar-radius) var(--chart-bar-radius) 0 0);      }    }    /* A waterfall's step up and step down: the two status inks, beside the sign written with the value. */    &.chart-bar-rise {      --chart-bar-color: var(--color-success);    }    &.chart-bar-fall {      --chart-bar-color: var(--color-danger);    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* A point of a line or a scatter: a dot of its color with a ring of the surface, so it reads where lines cross. */  .chart-dot {    r: var(--chart-dot);    fill: var(--category-mark, var(--chart-color));    stroke: var(--chart-surface);    stroke-width: 2px;    paint-order: stroke;    vector-effect: non-scaling-stroke;    pointer-events: none;    /* Shown only while its point is under the pointer or has the focus. */    &.chart-dot-quiet {      opacity: 0;    }    /* A bubble: a wash of its color inside an edge of it, so bubbles that overlap show through each other. */    &.chart-dot-bubble {      fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) 34%, transparent);      stroke: var(--category-mark, var(--chart-color));      stroke-width: 1.5px;      paint-order: normal;    }    /* A reading far from the others in a box plot: small and hollow. */    &.chart-dot-outlier {      r: 2.5px;      fill: var(--chart-surface);      stroke: var(--category-mark, var(--chart-color));      stroke-width: 1.5px;      paint-order: normal;    }  }  /* In a radial canvas a length is a share of the square: a dot there is drawn by its own r. */  .chart-canvas .chart-dot {    r: 1.7px;  }  /* A value written at a bar's end. */  .chart-value {    fill: var(--color-text-body);    stroke: none;    text-anchor: middle;    transform: translate(0, -.4375rem);    pointer-events: none;    &.chart-value-across {      text-anchor: start;      dominant-baseline: central;      transform: translate(.5rem, 0);    }    /* Before the plot, ending at its edge: a slope's value at its first end. */    &.chart-value-before {      text-anchor: end;      dominant-baseline: central;      transform: translate(-.5rem, 0);    }    /* On a tile, from its first corner: its name. */    &.chart-value-tile {      fill: var(--color-text-strong);      font-weight: var(--font-weight-control);      text-anchor: start;      dominant-baseline: hanging;      transform: translate(.5rem, .5625rem);    }    /* Under a tile's name: its value, quieter. */    &.chart-value-quiet {      fill: var(--color-text-muted);      font-weight: 400;      transform: translate(.5rem, 1.5625rem);    }    /* Its fill is named from a token, an author color: in forced colors every value takes the system's text. */    @media (forced-colors: active) {      fill: CanvasText;    }  }  /* A slice of a pie or a donut. It opens from the center when it first appears. */  .chart-slice {    /* A slice of an outer ring takes a share of its part's color, --chart-tone. */    fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) var(--chart-tone, 100%), var(--chart-surface));    stroke: transparent;    stroke-width: 0;    stroke-linejoin: round;    vector-effect: non-scaling-stroke;    paint-order: stroke;    transition: opacity 480ms var(--easing-glide) calc(min(var(--chart-index, 0), 12) * 40ms), scale 640ms var(--easing-glide) calc(min(var(--chart-index, 0), 12) * 40ms);    @starting-style {      opacity: 0;      scale: .9;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* A ring's track: the whole it is read against, in a tint of its color. */  .chart-track {    fill: none;    stroke: color-mix(in oklab, var(--category-mark, var(--chart-color)) 16%, transparent);    pointer-events: stroke;  }  /* A ring's value: it fills from the top, with round ends. */  .chart-arc {    fill: none;    stroke: var(--category-mark, var(--chart-color));    stroke-linecap: round;    stroke-dasharray: 1;    stroke-dashoffset: 0;    pointer-events: stroke;    transition: stroke-dashoffset 900ms var(--easing-glide) calc(min(var(--chart-index, 0), 12) * 80ms);    @starting-style {      stroke-dashoffset: 1;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* A radar's web: a ring at each tick and a spoke to each name. */  .chart-web {    fill: none;    stroke: var(--color-line-contour);    stroke-width: 1px;    stroke-linejoin: round;    vector-effect: non-scaling-stroke;    @media (forced-colors: active) {      stroke: GrayText;    }  }  /* A radar's series: its outline, with a wash of the same color that lets the others show through. */  .chart-shape {    fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) 14%, transparent);    stroke: var(--category-mark, var(--chart-color));    stroke-width: var(--chart-stroke);    stroke-linejoin: round;    vector-effect: non-scaling-stroke;    transition: opacity 480ms var(--easing-glide), scale 720ms var(--easing-glide);    @starting-style {      opacity: 0;      scale: .6;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* What a line's values may be: a band between their lower and upper ends, behind the line. */  .chart-band {    fill: color-mix(in oklab, var(--category-mark, color-mix(in oklab, var(--chart-color) 55%, transparent)) 18%, transparent);    stroke: none;    transition: opacity 720ms var(--easing-glide);    @starting-style {      opacity: 0;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* A stem: a lollipop's line from the baseline to its dot, and the line between a dumbbell's ends. */  .chart-stem {    stroke: color-mix(in oklab, var(--category-mark, var(--chart-color)) 42%, var(--chart-surface));    stroke-width: 2px;    stroke-linecap: round;    pointer-events: none;  }  /* A whisker: from the lowest to the highest a value may be, through a bar's end or a box. */  .chart-whisker {    /* Halfway between the ink and the surface, so it reads over a bar of ink and over the plot alike. */    stroke: color-mix(in oklab, var(--chart-color) 52%, var(--chart-surface));    stroke-width: 1.5px;    pointer-events: none;  }  /* A box plot's box: from the first quartile to the third. */  .chart-box {    fill: var(--category-mark, var(--chart-color));    stroke: none;    clip-path: inset(0 round calc(var(--chart-bar-radius) * .75));  }  /* The median: a line of the surface cut through the box. */  .chart-median {    stroke: var(--chart-surface);    stroke-width: 2px;    pointer-events: none;  }  /* A waterfall's hairline from one bar's end to the next bar. */  .chart-link {    fill: none;    stroke: var(--color-line-mark);    stroke-width: 1px;    vector-effect: non-scaling-stroke;    shape-rendering: crispEdges;    @media (forced-colors: active) {      stroke: GrayText;    }  }  /* A point of a slope or a bump: a round end of no length, so it stays a circle in a canvas that stretches. */  .chart-knot {    fill: none;    stroke: var(--category-mark, var(--chart-color));    stroke-width: calc(var(--chart-dot) * 2);    stroke-linecap: round;    vector-effect: non-scaling-stroke;    pointer-events: none;  }  /* A heatmap's cell: as much of its color as its value is of the range, --chart-tone, parted from its neighbors. */  .chart-cell {    fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) var(--chart-tone, 100%), var(--chart-surface));    stroke: none;    clip-path: inset(1px round 3px);    @media (forced-colors: active) {      forced-color-adjust: none;    }  }  /* Under the pointer a cell takes the gap around it. */  @media (hover: hover) {    .chart-point:hover .chart-cell {      clip-path: inset(0 round 3px);    }  }  /* A waffle's unit: one percent of the whole. */  .chart-unit {    fill: var(--category-mark, var(--chart-color));    stroke: none;    clip-path: inset(1.5px round 3px);    transition: opacity 400ms var(--easing-glide) calc(min(var(--chart-index, 0), 12) * 60ms);    @starting-style {      opacity: 0;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* A funnel's stage: a step lighter than the stage before it. */  .chart-stage {    fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) var(--chart-tone, 100%), var(--chart-surface));    stroke: transparent;    stroke-width: 0;    stroke-linejoin: round;    vector-effect: non-scaling-stroke;    transition: opacity 480ms var(--easing-glide) calc(min(var(--chart-index, 0), 12) * 60ms);    @starting-style {      opacity: 0;    }    @media (prefers-reduced-motion: reduce) {      transition: none;    }  }  /* A treemap's tile: a tint that holds its name, in its category's surface or a wash of ink. */  .chart-tile {    fill: var(--category-surface, color-mix(in oklab, var(--chart-color) 7%, var(--chart-surface)));    stroke: none;    clip-path: inset(1px round calc(var(--chart-bar-radius) * 1.25));  }  @media (hover: hover) {    .chart-point:hover .chart-tile {      fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) 16%, var(--chart-surface));    }  }  .chart-point:focus .chart-tile {    fill: color-mix(in oklab, var(--category-mark, var(--chart-color)) 16%, var(--chart-surface));  }  /* What stands in a donut's hole or within rings: a figure and what it counts. */  .chart-center {    position: absolute;    inset: 0;    display: grid;    place-content: center;    justify-items: center;    gap: .125rem;    text-align: center;    pointer-events: none;  }  .chart-center-value {    margin: 0;    color: var(--color-text-strong);    font: 400 1.5rem/1.15 var(--font-family-sans);    font-feature-settings: inherit;    /* The shorthand resets the chart's figures; a figure that changes keeps its width. */    font-variant-numeric: tabular-nums;    letter-spacing: -.02em;  }  .chart-center-label {    margin: 0;    font-size: .75rem;    line-height: 1.3;  }  /*   * The readout beside the point under the pointer: the point's name, then a row for each series with a stroke   * of its color, its name and its value. It stands at --chart-x and --chart-y of the plot, past the point's   * marks (--chart-reach) on the side with more room, and slides along its own height so it never leaves the plot.   */  .chart-tip {    --chart-tip-gap: .75rem;    /* 0 while the point is in the first half of the plot, 1 in the second: which side the readout stands on. */    --chart-tip-side: clamp(0, (var(--chart-x, 0) - .5) * 1000, 1);    position: absolute;    top: calc(var(--chart-y, 0) * 100%);    left: calc((var(--chart-x, 0) + var(--chart-reach, 0) * (1 - 2 * var(--chart-tip-side))) * 100%);    z-index: 1;    display: grid;    grid-template-columns: auto minmax(0, 1fr) auto;    column-gap: .4375rem;    row-gap: .1875rem;    align-items: center;    width: max-content;    min-width: 5.5rem;    max-width: 16rem;    margin: 0;    padding: .4375rem .625rem .5rem;    border-radius: calc(var(--radius-control-sm) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: var(--color-surface-tip);    color: light-dark(var(--color-text-inverse), var(--color-text-strong));    box-shadow: var(--shadow-tip);    font-size: .75rem;    line-height: 1.35;    white-space: nowrap;    translate: calc(var(--chart-tip-side) * (-100% - 2 * var(--chart-tip-gap)) + var(--chart-tip-gap)) calc(var(--chart-y, 0) * -100%);    pointer-events: none;    transition-property: opacity, display, top, left, translate;    transition-duration: var(--duration-quick);    transition-timing-function: var(--easing-glide);    transition-behavior: allow-discrete;    @starting-style {      opacity: 0;    }    &[hidden] {      display: none;      opacity: 0;    }    @media (prefers-reduced-motion: reduce) {      transition-property: opacity, display;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }  /*   * Over bars that run across, the readout stands under the row in the upper half of the plot and over it in the   * lower half, clear of the bar by --chart-reach, and slides along its own width.   */  .chart-body:has(.chart-bar-across) .chart-tip {    --chart-tip-gap: .375rem;    --chart-tip-under: clamp(0, (.5 - var(--chart-y, 0)) * 1000, 1);    top: calc((var(--chart-y, 0) + var(--chart-reach, 0) * (2 * var(--chart-tip-under) - 1)) * 100%);    left: calc(var(--chart-x, 0) * 100%);    translate: calc(var(--chart-x, 0) * -100%) calc(var(--chart-tip-under) * (100% + 2 * var(--chart-tip-gap)) - 100% - var(--chart-tip-gap));  }  /* In a square the readout stands on the point and slides along both of its sides. */  .chart-body:has(.chart-plot-radial) .chart-tip {    left: calc(var(--chart-x, 0) * 100%);    translate: calc(var(--chart-x, 0) * -100%) calc(var(--chart-y, 0) * -100%);  }  .chart-body:has(.chart-plot-radar) .chart-tip {    top: calc(var(--chart-y, 0) * var(--chart-side));    left: calc(50% + (var(--chart-x, 0) - .5) * var(--chart-side));    translate: calc(var(--chart-x, 0) * -100%) calc(var(--chart-y, 0) * -100%);  }  /*   * In a donut or rings the readout takes the middle: the value as the figure and the series' name under it,   * in the place of what the middle held, so nothing covers the marks.   */  .chart-body:has(.chart-center) {    .chart-tip {      inset: 0;      grid-template-columns: auto auto;      place-content: center;      column-gap: .3125rem;      row-gap: .125rem;      width: auto;      min-width: 0;      max-width: none;      padding: 0;      background: none;      color: var(--color-text-muted);      box-shadow: none;      translate: none;      transition-property: opacity, display;      @media (forced-colors: active) {        outline: none;      }    }    .chart-tip-value {      grid-row: 1;      grid-column: 1 / -1;      padding: 0;      color: var(--color-text-strong);      font: 400 1.5rem/1.15 var(--font-family-sans);      font-feature-settings: inherit;      /* The shorthand resets the readout's tabular figures, which keep the value still as the point changes. */      font-variant-numeric: tabular-nums;      letter-spacing: -.02em;      text-align: center;    }    .chart-tip-key {      grid-row: 2;      width: .5rem;      height: .5rem;      border-radius: 50%;    }    .chart-tip-name {      grid-row: 2;      color: inherit;    }    &:has(.chart-tip:not([hidden])) .chart-center {      visibility: hidden;    }  }  .chart-tip-title {    grid-column: 1 / -1;    margin: 0 0 .0625rem;    color: color-mix(in oklab, currentColor 64%, transparent);    font-size: .6875rem;  }  /* One series of the readout. Its parts stand in the readout's columns. */  .chart-tip-row {    display: contents;    margin: 0;  }  /* A short stroke of the series' color. */  .chart-tip-key {    width: .625rem;    height: .125rem;    border-radius: 1px;    corner-shape: round;    background: var(--category-mark, currentColor);    /*     * It keeps its series' color in forced colors, as the legend's mark does, instead of the forced canvas. A     * series with no category is the system's text, as its marks are, not the readout's own ink.     */    @media (forced-colors: active) {      forced-color-adjust: none;      background: var(--category-mark, CanvasText);    }  }  .chart-tip-name {    overflow: hidden;    color: color-mix(in oklab, currentColor 76%, transparent);    text-overflow: ellipsis;  }  .chart-tip-value {    padding-inline-start: .625rem;    font-weight: var(--font-weight-control);    font-variant-numeric: tabular-nums;    text-align: end;  }  /* The legend: the name of each series beside a mark of its color. */  .chart-legend {    display: flex;    flex-wrap: wrap;    gap: .125rem 1rem;    min-width: 0;    margin: 0;    padding: 0;    /* The entries' touch targets stand behind them, within the legend. */    isolation: isolate;    color: var(--color-text-body);    font-size: .75rem;    line-height: 1.35;    list-style: none;  }  /* One entry. With a checkbox in it, it shows and hides its series. */  .chart-key {    position: relative;    display: inline-flex;    align-items: center;    gap: .4375rem;    min-height: 1.5rem;    margin: 0;    padding: 0;    &:has(.chart-key-input) {      border-radius: calc(var(--radius-chip) * var(--corner-scale));      corner-shape: var(--corner-shape);      cursor: pointer;      user-select: none;      -webkit-user-select: none;      -webkit-tap-highlight-color: transparent;      @media (hover: hover) {        &:hover {          color: var(--color-text-strong);        }      }    }    /* A hidden series: its name steps back and its mark is an outline. */    &:has(.chart-key-input:not(:checked)) {      color: var(--color-text-disabled);      .chart-key-mark {        background: transparent;        box-shadow: inset 0 0 0 1.5px var(--color-line-mark);      }      .chart-key-value {        visibility: hidden;      }      /* It can still be shown again: under the pointer its name comes a step forward, as a shown one's does. */      @media (hover: hover) {        &:hover {          color: var(--color-text-muted);        }      }      /* Forced colors would make the name the text color again and the outline an author color: both are the system's gray. */      @media (forced-colors: active) {        &, &:hover {          color: GrayText;        }        .chart-key-mark {          box-shadow: inset 0 0 0 1.5px GrayText;        }      }    }    &:has(.chart-key-input:focus-visible) {      @apply --focus-ring;      @media (forced-colors: active) {        outline-color: Highlight;      }    }    /*     * A finger's target reaches above and below the entry, behind every entry, so where it overlaps the entry     * beside or under it in a column or a wrapped row, the entry that is seen is the one that is touched.     */    @media (pointer: coarse) {      &:has(.chart-key-input)::after {        @apply --touch-target-block;        z-index: -1;      }    }  }  /* The checkbox: it keeps its place in the tab order and its name, and the entry is what is seen. */  .chart-key-input {    position: absolute;    inset: 0;    width: 100%;    height: 100%;    margin: 0;    padding: 0;    border: 0;    appearance: none;    opacity: 0;    cursor: inherit;  }  /* The mark: a small block of the series' color, as a bar, an area or a slice is. */  .chart-key-mark {    flex: none;    width: .625rem;    height: .625rem;    border-radius: calc(.1875rem * var(--corner-scale));    corner-shape: var(--corner-shape);    background: var(--category-mark, var(--chart-color));    /* A short stroke, as a line is. */    &.chart-key-line {      width: .875rem;      height: .125rem;      border-radius: 1px;      corner-shape: round;    }    /* A dot, as a scatter's point is. */    &.chart-key-dot {      width: .5rem;      height: .5rem;      border-radius: 50%;      corner-shape: round;    }    @media (forced-colors: active) {      forced-color-adjust: none;    }  }  /* A figure after the name: a slice's share, a ring's value. */  .chart-key-value {    color: var(--color-text-muted);    font-variant-numeric: tabular-nums;  }}