指南

核心概念

适用于每种图表类型的理念——数据如何成形、轴如何缩放、如何主题化、事件系统、导出、响应式设计、无障碍和动画。

数据格式

数字数组——每个值是y;x从0(或pointStart)自增。

series: [{ data: [10, 20, 30, 40, 50] }]
// points: (0,10), (1,20), (2,30), (3,40), (4,50)

元组——[x, y],或[x, y, z]用于气泡图(z = 半径),或[name, y]用于饼图/分类数据。

data: [[0, 10], [5, 20], [12, 35]]          // [x, y]
data: [[0, 10, 50], [5, 20, 120]]          // [x, y, z] bubble
data: [['Apples', 5], ['Oranges', 3]]      // [name, y]

对象(PointOptions)——最灵活;每个点携带命名属性。

data: [{
  x: 0, y: 10, name: 'First', color: '#d62728', id: 'point-0',
  drilldown: 'details-0',
  marker: { symbol: 'diamond', radius: 6 },
  dataLabels: { enabled: true, format: '{y} units' },
  custom: { department: 'Sales', quarter: 'Q1' }
}]

空值默认会断开线;connectNulls: true可跨越间隙。pointStart / pointInterval将平面数组映射到x轴(适合日期时间)。keys重新映射元组列。

{ data: [10, 20, null, 40], connectNulls: true }
{ data: [29.9, 71.5, 106.4], pointStart: Date.UTC(2024,0,1), pointInterval: 86400000 }
{ keys: ['x', 'y', 'color'], data: [[0, 10, '#d62728'], [1, 25, '#2ca02c']] }

按类型的特殊格式

类型格式
pie{ name, y }
candlestick / ohlc{ x, open, high, low, close }
boxplot{ low, q1, median, q3, high }
sankey{ from, to, weight }
heatmap{ x, y, value }
treemap / sunburst{ id, parent, name, value }
networkgraph[nodeA, nodeB] pairs
gauge[{ y: value }]

轴系统

每条轴使用四种标度类型之一;类型从数据推断或通过xAxis.type/yAxis.type设置。

类型描述
linear连续数值标度。
logarithmic对数基数10,用于指数范围。
datetime具有智能日期刻度标记的时间标度。
category每个类别标签的离散条带。
设置xAxis.categories自动使轴成为分类轴。

定义域计算(按顺序应用)

  • minPadding / maxPadding——比例边缘空白(0.01线性,0分类)。
  • softMin / softMax——仅在数据未达到时扩展。
  • floor / ceiling——硬限制定义域无法跨越(但可以更小)。
  • min / max——显式硬覆盖。
  • startOnTick / endOnTick——向外舍入到最近的刻度。

多轴

yAxis: [
  { title: { text: 'Temperature (°C)' } },
  { title: { text: 'Rainfall (mm)' }, opposite: true }
],
series: [
  { name: 'Temperature', type: 'line',   yAxis: 0, data: [7,12,18,24] },
  { name: 'Rainfall',    type: 'column', yAxis: 1, data: [49,71,106,129] }
]

样式和主题化

series颜色来自调色板——通过setOptions({ colors })全局设置或按图表设置。20个调色板内置(见API)。

KatuCharts.setOptions({ colors: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'] });
KatuCharts.chart(container, { colors: ['#264653', '#2a9d8f', '#e9c46a'], series: [/* … */] });

虚线样式

dashStylestroke-dasharray
Solidnone
Dash8,6
Dot2,6
DashDot8,6,2,6
ShortDash / ShortDot6,2 / 2,2
ShortDashDot / ShortDashDotDot6,2,2,2 / 6,2,2,2,2,2
LongDash / LongDashDot / LongDashDotDot16,6 / 16,6,2,6 / 16,6,2,6,2,6

CSS类钩子

每个元素都获得可预测的类用于外部样式——例如.katucharts-background、.katucharts-title、.katucharts-axis、.katucharts-grid-line、.katucharts-series、.katucharts-point、.katucharts-legend-item、.katucharts-tooltip、.katucharts-data-label、.katucharts-crosshair、.katucharts-credits、.katucharts-export-button。

交互性

chart: {
  zoomType: 'xy',                       // 'x' | 'y' | 'xy'
  panning: { enabled: true, type: 'xy' },
  panKey: 'shift',
  zooming: {
    mouseWheel: { enabled: true, sensitivity: 1.1 },
    resetButton: { position: { align: 'right', y: 10 } }
  }
}
  • 钻取——点击带有drilldown id的点以下钻到子series;出现返回按钮。级别可以嵌套。
  • 十字准线——xAxis.crosshair: { width, color, dashStyle, snap }跟踪指针。
  • 点选择——allowPointSelect: true带有states.select样式和point.events.select/unselect。
  • 悬停——线/标记增长、透明度、光晕通过states.hover;非悬停series通过states.inactive变暗。

事件系统

处理程序附加在图表、series、点和轴级别。在处理程序内this是相关对象。

chart: { events: { load() {}, redraw() {}, render() {}, click(e) {},
  selection(e) {}, drilldown(e) {}, drillup(e) {} } },
plotOptions: { series: { events: {
  click(e) {}, mouseOver() {}, mouseOut() {}, legendItemClick() { return true; },
  show() {}, hide() {}, afterAnimate() {}
}, point: { events: {
  click() {}, select() {}, unselect() {}, update(e) {}, remove() {}
} } } },
xAxis: { events: { afterSetExtremes(e) { /* e.min, e.max, e.trigger */ } } }

内部EventBus

const chart = KatuCharts.chart(container, options);
const unsub = chart.events.on('point:click', d => console.log(d.point, d.series));
chart.events.on('zoom:changed', d => console.log(d.xMin, d.xMax));
unsub();
事件负载
chart:load / redraw / render图表实例
chart:click{ x, y, originalEvent }
chart:addSeries{ series, options }
point:mouseover / mouseout / click{ point, series, originalEvent }
series:mouseenter / mouseleave{ series, originalEvent }
series:visibilityChanged / legend:itemClick{ series, visible }
navigator:brushed{ min, max }
rangeSelector:selected / dateRange{ index, text } / { min, max }
zoom:changed{ xMin, xMax, yMin, yMax, trigger }
drilldown:drilldown / drillup{ point, seriesOptions } / { seriesOptions }

导出和数据访问

chart.exportChart({ type: 'image/png', filename: 'my-chart' });
// 'image/svg+xml' · 'image/jpeg' · 'application/pdf' (needs jspdf)

const svg  = chart.getSVG();
const csv  = chart.getCSV();
const html = chart.getTable();
const rows = chart.getDataRows();       // header row first

// the export menu can also offer CSV and XLS downloads:
// exporting: { buttons: { contextButton: { menuItems: [
//   'downloadPNG', 'downloadJPEG', 'downloadSVG', 'downloadPDF', 'downloadCSV', 'downloadXLS'
// ] } } }

import { ExportModule } from 'katucharts.js';
ExportModule.exportPNG(chart.getSVG(), 'my-chart', 2);   // svg string, filename, scale
ExportModule.exportPDF(chart.getSVG(), 'my-chart');      // needs jspdf

股票图表

核心包中的金融图表提供范围选择器和导航器(rangeSelector.enabled、navigator.enabled)、OHLC/K线渲染和数据分组。

import KatuCharts from 'katucharts.js';

KatuCharts.chart(container, {
  rangeSelector: { enabled: true, selected: 1, buttons: [
    { type: 'month', count: 1, text: '1m' },
    { type: 'year',  count: 1, text: '1y' },
    { type: 'all', text: 'All' }
  ] },
  navigator: { enabled: true },
  series: [{
    type: 'candlestick', name: 'AAPL', data: ohlc,
    dataGrouping: { units: [['week', [1]], ['month', [1, 3, 6]]] }
  }]
});

数据分组近似

近似描述
average / sum组的平均值 / 总和。
open / close组中的第一个 / 最后一个值。
high / low组的最大值 / 最小值。
ohlc将开、高、低、收合并为一个OHLC点。

响应式设计

一个ResizeObserver在容器调整大小时自动调用reflow()——图表适配flex/grid布局无需手动工作。添加responsive.rules用于条件覆盖。

自动高度——不设置 chart.height(null)时,图表会增长以适应内容而非收缩;在较矮的移动视口中增长有上限。可与 chart.scrollablePlotArea 结合,让密集图表在小屏幕上保持清晰。

responsive: {
  rules: [
    { condition: { maxWidth: 500 },
      chartOptions: { legend: { enabled: false }, credits: { enabled: false } } },
    { condition: { callback: () => matchMedia('(max-width: 600px)').matches },
      chartOptions: { chart: { spacing: [5, 5, 5, 5] } } }
  ]
}

无障碍

  • ARIA——容器获得role="img" + 描述性aria-label。
  • 描述——一个隐藏文本块为屏幕阅读器总结数据。
  • 键盘——Tab键浏览series/点,Enter选择,Escape退出。
  • 实时区域——动态更新通过aria-live公告。
  • 焦点管理和高对比度——焦点指示器和基于形状的分化。
accessibility: {
  enabled: true,
  description: 'Line chart of monthly revenue, Jan–Jun 2024.',
  keyboardNavigation: { enabled: true, focusBorder: { style: { color: '#00f', lineWidth: 2 } } },
  point: { descriptionFormatter: p => p.series.name + ': ' + p.y + ' at ' + p.category },
  announceNewData: { enabled: true, minAnnounceInterval: 5000 }
}

动画

KatuCharts.setOptions({ chart: { animation: { duration: 800, easing: 'easeOutCubic' } } });
// per-series
series: [{ data: [10,20,30], animation: { duration: 1200, easing: 'easeInOutQuart' } },
         { data: [8,15,22], animation: false }]
// animated update
chart.series[0].setData([50,60,70,80], false);
chart.animatedRedraw(600);

按类型的进入动画

类型样式持续时间
line / splineStroke draw (path reveal)1000ms
areaStroke draw + fill fade-in1000ms
column / barGrow from baseline + stagger800ms + 80ms/bar
scatter / bubbleStagger fade-in / scale-in600ms + 20–40ms/pt
pieRotate sweep600ms
heatmap / waterfallFade / grow + stagger600–800ms + per-cell/bar
错开动画上限500个点;超过此数,所有点同时动画以提高性能。