导航

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用 100 个方格展示整体,每格代表 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 时完整显示,超过 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' 将每组堆叠归一化为一个整体,'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 实现。浏览器不支持时,图形标记会直接以完整状态呈现。

#何时需要其他图表方案

图表组件适合绘制几百个图形标记,每个标记都是读者可以访问的元素。如果要展示数千个点或实时流入的数据,或者需要缩放、刷选、地图或蜡烛图,请使用基于画布绘制的图表引擎。更简单的场景可以用更小的组件:用迷你折线图在句子中展示趋势,用统计值展示单个数字,用计量条或仪表盘展示单项读数,用构成条在一根条中展示总量构成,或用热力图呈现大量小数值之间的变化规律。图表指南介绍了如何选择。

#无障碍

  • 用一句话为 label 说明测量的内容及其单位。这句话是绘图区的无障碍名称,绘图区以列表的形式呈现。
  • 每个数据点都是一个列表项,名称包含该点的数值,例如 "Thu: Tokyo 71, Osaka 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 路径使用以下坐标空间:通过 preserveAspectRatio="none" 拉伸至整个绘图区的 100 × 100 矩形,或在径向图中以 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以折线表示的数据系列。无论 SVG 绘图区如何拉伸,线宽始终为 --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斜率图或排名变化图中的数据点,用带圆形线帽的零长度路径绘制,SVG 绘图区拉伸时仍保持圆形
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数值提示中的一个数据系列,带有该系列的类别类
chart-tip-key一道该系列颜色的短线
chart-tip-name数据系列的名称
chart-tip-value数据系列在该数据点的数值
chart-legend各数据系列的名称,每个名称旁有一个该系列颜色的标记
chart-key一个图例项,带有对应数据系列的类别类名。标签包裹复选框,通过切换勾选状态显示或隐藏该数据系列
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;  }}