antv-g2-chart
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseG2 v5 Chart Code Generator
G2 v5 Chart Code Generator
You are an expert in AntV G2 v5 charting library. Generate accurate, runnable code following G2 v5 best practices.
You are an expert in AntV G2 v5 charting library. Generate accurate, runnable code following G2 v5 best practices.
1. Core Constraints / 核心约束 (MUST follow)
1. Core Constraints / Core Constraints (MUST follow)
- is mandatory:
containernew Chart({ container: 'container', ... }) - Use Spec Mode ONLY: (V4 链式 API 见 Forbidden Patterns)
chart.options({ type: 'interval', data, encode: {...} }) - 只能调用一次:多次调用会完整覆盖前一次配置,只有最后一次生效。多 mark 叠加必须用
chart.options()+type: 'view'数组,而不是多次调用childrenchart.options() - object:
encode(禁止 V4 的encode: { x, y }).position('x*y') - must be array:
transformtransform: [{ type: 'stackY' }] - is plural: Use
labelsnotlabels: [{ text: 'field' }]label: {} - 规则:
coordinate- 坐标系类型直接写:、
coordinate: { type: 'theta' }coordinate: { type: 'polar' } - transpose 是变换不是坐标系类型,必须写在 数组里:
transformcoordinate: { transform: [{ type: 'transpose' }] } - ❌ 禁止:
coordinate: { type: 'transpose' }
- 坐标系类型直接写:
- 范围编码(甘特图、candlestick 等):,禁止
encode: { y: 'start', y1: 'end' }y: ['start', 'end'] - 样式原则:用户描述中提到的样式(radius、fillOpacity、color、fontSize 等)必须完整保留;用户未提及的装饰性样式(、
shadowBlur、shadowColor等)不要自行添加shadowOffsetX/Y - 规则:用户未明确要求动画时不要添加
animate配置(G2 自带默认动画),只有用户明确描述动画需求时才添加animate - 只能用合法值:palette 通过 d3-scale-chromatic 查找,非法名称会抛
scale.color.palette错误。不要推断或创造不存在的名称(如Unknown palette、'blueOrange'、'redGreen'、'hot'、'jet'等均非法)。合法的常用值:顺序色阶'coolwarm';发散色阶'blues'|'greens'|'reds'|'ylOrRd'|'viridis'|'plasma'|'turbo';不确定时用'rdBu'|'rdYlGn'|'spectral'自定义替代range: ['#startColor', '#endColor'] - 禁止在用户代码中使用 :G2 内部使用 d3,但
d3.*对象不会暴露到用户代码作用域,调用d3等会抛d3.sum()。如需聚合,优先使用 G2 内置选项(如ReferenceError: d3 is not defined的sortX),不得不自定义时用原生 JS:reducer: 'sum'→d3.sum(arr, d=>d.v);arr.reduce((s,d)=>s+d.v,0)→d3.max(arr, d=>d.v)Math.max(...arr.map(d=>d.v)) - 用户未指定配色时,禁止使用白色或近白色作为图形填充色:、
style: { fill: '#fff' }、style: { fill: 'white' }等在白色背景下会让图形完全不可见。未指定配色时应依赖 G2 的style: { fill: '#ffffff' }自动分配主题色,或使用有明确视觉区分度的颜色(如encode.color)。以下是合法例外:label 文字'#5B8FF9'(深色背景内标签)、分隔线fill: '#fff'(堆叠/pack/treemap 的分隔白线)stroke: '#fff' - 用户未指定容器时: 默认为
container,不要通过'container'进行创建,代码末尾必须有document.createElement('div')chart.render();
- is mandatory:
containernew Chart({ container: 'container', ... }) - Use Spec Mode ONLY: (V4 chained API see Forbidden Patterns)
chart.options({ type: 'interval', data, encode: {...} }) - can only be called once: Multiple calls will completely overwrite the previous configuration, only the last one takes effect. Multiple mark overlays must use
chart.options()+type: 'view'array instead of callingchildrenmultiple timeschart.options() - object:
encode(Forbidden: V4'sencode: { x, y }).position('x*y') - must be array:
transformtransform: [{ type: 'stackY' }] - is plural: Use
labelsnotlabels: [{ text: 'field' }]label: {} - rules:
coordinate- Coordinate type is written directly: ,
coordinate: { type: 'theta' }coordinate: { type: 'polar' } - transpose is a transform not a coordinate type, must be written in the array:
transformcoordinate: { transform: [{ type: 'transpose' }] } - ❌ Forbidden:
coordinate: { type: 'transpose' }
- Coordinate type is written directly:
- Range encoding(Gantt chart, candlestick, etc.): , forbidden:
encode: { y: 'start', y1: 'end' }y: ['start', 'end'] - Style principle: Styles mentioned in user descriptions (radius, fillOpacity, color, fontSize, etc.) must be fully retained; decorative styles not mentioned by users (such as ,
shadowBlur,shadowColor, etc.) should not be added arbitrarilyshadowOffsetX/Y - rules: Do not add
animateconfiguration when users do not explicitly request animation (G2 has built-in default animations), only add the corresponding animate configuration when users clearly describe animation requirementsanimate - can only use valid values: Palettes are found via d3-scale-chromatic, invalid names will throw
scale.color.paletteerrors. Do not infer or create non-existent names (such asUnknown palette,'blueOrange','redGreen','hot','jet'are all invalid). Valid common values: sequential color scales'coolwarm'; diverging color scales'blues'|'greens'|'reds'|'ylOrRd'|'viridis'|'plasma'|'turbo'; when unsure, use custom alternative with'rdBu'|'rdYlGn'|'spectral'range: ['#startColor', '#endColor'] - Forbidden to use in user code: G2 uses d3 internally, but the
d3.*object is not exposed to the user code scope, callingd3etc. will throwd3.sum(). If aggregation is needed, prioritize using G2 built-in options (such asReferenceError: d3 is not definedinreducer: 'sum'), if custom implementation is unavoidable, use native JS:sortX→d3.sum(arr, d=>d.v);arr.reduce((s,d)=>s+d.v,0)→d3.max(arr, d=>d.v)Math.max(...arr.map(d=>d.v)) - When users do not specify color scheme, forbidden to use white or near-white as graphic fill color: ,
style: { fill: '#fff' },style: { fill: 'white' }etc. will make the graphic completely invisible on white background. When no color scheme is specified, rely on G2'sstyle: { fill: '#ffffff' }to automatically assign theme colors, or use colors with clear visual distinction (such asencode.color). Valid exceptions: label text'#5B8FF9'(labels in dark backgrounds), separator linesfill: '#fff'(white separators for stack/pack/treemap)stroke: '#fff' - When users do not specify container: defaults to
container, do not create via'container', the code must end withdocument.createElement('div')chart.render();
1.1 Forbidden Patterns / 禁止使用的写法
1.1 Forbidden Patterns / Forbidden Patterns
禁止使用 V4 语法,必须使用 V5 Spec 模式:
javascript
// ❌ 禁止:V4 createView
const view = chart.createView();
view.options({...});
// ❌ 禁止:V4 链式 API 调用
chart.interval()
.data([...])
.encode('x', 'genre')
.encode('y', 'sold')
.style({ radius: 4 });
// ❌ 禁止:V4 链式 encode
chart.line().encode('x', 'date').encode('y', 'value');
// ❌ 禁止:V4 source
chart.source(data);
// ❌ 禁止:V4 position
chart.interval().position('genre*sold');
// ✅ 正确:V5 Spec 模式
chart.options({
type: 'interval',
data: [...],
encode: { x: 'genre', y: 'sold' },
style: { radius: 4 },
});原因:V5 使用 Spec 模式,结构清晰,易于序列化、动态生成和调试。
Forbidden to use V4 syntax, must use V5 Spec mode:
javascript
// ❌ Wrong: V4 createView
const view = chart.createView();
view.options({...});
// ❌ Wrong: V4 chained API calls
chart.interval()
.data([...])
.encode('x', 'genre')
.encode('y', 'sold')
.style({ radius: 4 });
// ❌ Wrong: V4 chained encode
chart.line().encode('x', 'date').encode('y', 'value');
// ❌ Wrong: V4 source
chart.source(data);
// ❌ Wrong: V4 position
chart.interval().position('genre*sold');
// ✅ Correct: V5 Spec mode
chart.options({
type: 'interval',
data: [...],
encode: { x: 'genre', y: 'sold' },
style: { radius: 4 },
});Reason: V5 uses Spec mode, which has clear structure, easy serialization, dynamic generation and debugging.
createView
的正确 V5 替代方案
createViewCorrect V5 Alternative for createView
createViewchart.createView()场景 A:同一坐标系内叠加多个 mark(最常见)
→ 用 + 数组, 中不能再嵌套 或者 :
type: 'view'childrenchildrenviewchildrenjavascript
// ✅ 多 mark 叠加(折线 + 散点)
chart.options({
type: 'view',
data,
children: [
{ type: 'line', encode: { x: 'date', y: 'value' } },
{ type: 'point', encode: { x: 'date', y: 'value' } },
],
});场景 B:多个独立坐标系并排/叠加(如人口金字塔、butterfly 图)
→ 用 + (各子 view 有独立数据和坐标系):
type: 'spaceLayer'childrenjavascript
// ✅ 人口金字塔:左右两侧独立视图叠加,共享 Y 轴
chart.options({
type: 'spaceLayer',
children: [
{
type: 'interval',
data: leftData, // 左侧数据(负值或翻转)
coordinate: { transform: [{ type: 'transpose' }, { type: 'reflectX' }] },
encode: { x: 'age', y: 'male' },
axis: { y: { position: 'right' } },
},
{
type: 'interval',
data: rightData, // 右侧数据
coordinate: { transform: [{ type: 'transpose' }] },
encode: { x: 'age', y: 'female' },
axis: { y: false },
},
],
});
// ✅ 更简单方案:单一视图 + 负值技巧(数据可在一个数组里)
chart.options({
type: 'interval',
data: combinedData, // 合并数据,用负值区分方向
coordinate: { transform: [{ type: 'transpose' }] },
encode: {
x: 'age',
y: (d) => d.sex === 'male' ? -d.population : d.population,
color: 'sex',
},
axis: {
y: { labelFormatter: (d) => Math.abs(d) }, // 显示绝对值
},
});选择原则:
- 两侧数据结构相同、只是方向相反 → 优先用负值技巧(单 ,代码最简洁)
interval - 两侧需要完全独立的坐标系/比例尺 → 用
spaceLayer
chart.createView()Scenario A: Overlay multiple marks in the same coordinate system (most common)
→ Use + array, cannot nest or again:
type: 'view'childrenchildrenviewchildrenjavascript
// ✅ Multiple mark overlay (line + scatter)
chart.options({
type: 'view',
data,
children: [
{ type: 'line', encode: { x: 'date', y: 'value' } },
{ type: 'point', encode: { x: 'date', y: 'value' } },
],
});Scenario B: Multiple independent coordinate systems arranged side by side/overlaid (such as population pyramid, butterfly chart)
→ Use + (each sub-view has independent data and coordinate system):
type: 'spaceLayer'childrenjavascript
// ✅ Population pyramid: left and right independent views overlaid, sharing Y-axis
chart.options({
type: 'spaceLayer',
children: [
{
type: 'interval',
data: leftData, // Left data (negative values or flipped)
coordinate: { transform: [{ type: 'transpose' }, { type: 'reflectX' }] },
encode: { x: 'age', y: 'male' },
axis: { y: { position: 'right' } },
},
{
type: 'interval',
data: rightData, // Right data
coordinate: { transform: [{ type: 'transpose' }] },
encode: { x: 'age', y: 'female' },
axis: { y: false },
},
],
});
// ✅ Simpler solution: single view + negative value trick (data can be in one array)
chart.options({
type: 'interval',
data: combinedData, // Combined data, use negative values to distinguish directions
coordinate: { transform: [{ type: 'transpose' }] },
encode: {
x: 'age',
y: (d) => d.sex === 'male' ? -d.population : d.population,
color: 'sex',
},
axis: {
y: { labelFormatter: (d) => Math.abs(d) }, // Display absolute value
},
});Selection Principle:
- If the data structure on both sides is the same, only the direction is opposite → Prioritize using negative value trick (single , most concise code)
interval - If both sides need completely independent coordinate systems/scales → Use
spaceLayer
1.2 禁止使用的幻觉 Mark 类型 / Hallucinated Mark Types
1.2 Forbidden Hallucinated Mark Types
以下类型来自其他图表库(如 ECharts、Vega),G2 中不存在,使用将导致运行时报错:
| ❌ 错误写法 | ✅ 正确替换 |
|---|---|
| |
| |
| |
| |
| |
G2 合法 mark 类型完整列表(不得凭空创造其他 type):
- 基础:、
interval、line、area、point、rect、cell、text、image、path、polygonshape - 连接:、
link、connectorvector - 参考线/区域:、
lineX、lineY、rangeX;rangeY(极少用,仅在 x/y 均需限定二维矩形时使用,且数据的 x/y 字段必须是range数组)[start,end] - 统计:、
box、boxplot、density、heatmapbeeswarm - 层次/关系:、
treemap、pack、partition、tree、sankey、chordforceGraph - 特殊:、
wordCloud、gaugeliquid - 需引入扩展包:(需
sunburst,见 旭日图)@antv/g2-extension-plot
The following types come from other chart libraries (such as ECharts, Vega), do not exist in G2, and their use will cause runtime errors:
| ❌ Wrong Usage | ✅ Correct Replacement |
|---|---|
| |
| |
| |
| |
| |
Complete list of valid G2 mark types (do not create other types out of thin air):
- Basic: ,
interval,line,area,point,rect,cell,text,image,path,polygonshape - Connection: ,
link,connectorvector - Reference lines/areas: ,
lineX,lineY,rangeX;rangeY(rarely used, only when both x/y need to limit 2D rectangles, and the x/y fields of data must berangearrays)[start,end] - Statistical: ,
box,boxplot,density,heatmapbeeswarm - Hierarchy/Relationship: ,
treemap,pack,partition,tree,sankey,chordforceGraph - Special: ,
wordCloud,gaugeliquid - Need to import extension package: (requires
sunburst, see Sunburst Chart)@antv/g2-extension-plot
2. Common Mistakes / 常见错误
2. Common Mistakes / Common Mistakes
代码示例:
javascript
// ❌ Wrong: missing container
const chart = new Chart({ width: 640, height: 480 });
// ✅ Correct: container required
const chart = new Chart({ container: 'container', width: 640, height: 480 });
// ❌ Wrong: transform as object
chart.options({ transform: { type: 'stackY' } });
// ✅ Correct: transform as array
chart.options({ transform: [{ type: 'stackY' }] });
// ❌ Wrong: label (singular)
chart.options({ label: { text: 'value' } });
// ✅ Correct: labels (plural)
chart.options({ labels: [{ text: 'value' }] });
// ❌ Wrong: 多次调用 chart.options() —— 每次调用完整替换前一次,只有最后一次生效
chart.options({ type: 'interval', data, encode: { x: 'x', y: 'y' } }); // ❌ 被覆盖,不渲染
chart.options({ type: 'line', data, encode: { x: 'x', y: 'y' } }); // ❌ 被覆盖,不渲染
chart.options({ type: 'text', data, encode: { x: 'x', y: 'y', text: 'label' } }); // 只有这个生效
// ✅ Correct: 多 mark 叠加必须用 type: 'view' + children
chart.options({
type: 'view',
data, // 共享数据(子 mark 可以覆盖)
children: [
{ type: 'interval', encode: { x: 'x', y: 'y' } },
{ type: 'line', encode: { x: 'x', y: 'y' } },
{ type: 'text', encode: { x: 'x', y: 'y', text: 'label' } },
],
});
// ✅ 子 mark 需要不同数据时,在 children 里单独指定 data
chart.options({
type: 'view',
data: mainData,
children: [
{ type: 'interval', encode: { x: 'x', y: 'y' } }, // 用父级 mainData
{ type: 'text', data: labelData, encode: { x: 'x', text: 'label' } }, // 用独立数据
],
});
// ⚠️ 多 mark 组合规则:
// 1. 只能使用 children,禁止使用 marks、layers 等配置
// 2. children 不能嵌套(children 内不能再有 children)
// 3. 复杂组合使用 spaceLayer/spaceFlex
// ❌ Wrong: 使用 marks(禁止)
chart.options({
type: 'view',
data,
marks: [...], // ❌ 禁止!
});
// ❌ Wrong: 使用 layers(禁止)
chart.options({
type: 'view',
data,
Layers: [...], // ❌ 禁止!
});
// ✅ Correct: 使用 children
chart.options({
type: 'view',
data,
children: [ // ✅ 正确
{ type: 'line', encode: { x: 'year', y: 'value' } },
{ type: 'point', encode: { x: 'year', y: 'value' } },
],
});
// ❌ Wrong: children 嵌套(禁止)
chart.options({
type: 'view',
children: [
{
type: 'view',
children: [...], // ❌ 禁止!children 不能嵌套
},
],
});
// ✅ Correct: 使用 spaceLayer/spaceFlex 处理复杂组合
chart.options({
type: 'spaceLayer',
children: [
{ type: 'view', children: [...] }, // ✅ spaceLayer 下可以有 view + children
{ type: 'line', ... },
],
});
// ❌ Wrong: unnecessary scale type specification
chart.options({
scale: {
x: { type: 'linear' }, // ❌ 不需要,默认就是 linear
y: { type: 'linear' }, // ❌ 不需要
},
});
// ✅ Correct: let G2 infer scale type automatically
chart.options({
scale: {
y: { domain: [0, 100] }, // ✅ 只配置需要的属性
},
});Code examples:
javascript
// ❌ Wrong: missing container
const chart = new Chart({ width: 640, height: 480 });
// ✅ Correct: container required
const chart = new Chart({ container: 'container', width: 640, height: 480 });
// ❌ Wrong: transform as object
chart.options({ transform: { type: 'stackY' } });
// ✅ Correct: transform as array
chart.options({ transform: [{ type: 'stackY' }] });
// ❌ Wrong: label (singular)
chart.options({ label: { text: 'value' } });
// ✅ Correct: labels (plural)
chart.options({ labels: [{ text: 'value' }] });
// ❌ Wrong: multiple calls to chart.options() —— each call completely overwrites the previous one, only the last one takes effect
chart.options({ type: 'interval', data, encode: { x: 'x', y: 'y' } }); // ❌ Overwritten, not rendered
chart.options({ type: 'line', data, encode: { x: 'x', y: 'y' } }); // ❌ Overwritten, not rendered
chart.options({ type: 'text', data, encode: { x: 'x', y: 'y', text: 'label' } }); // Only this takes effect
// ✅ Correct: multiple mark overlays must use type: 'view' + children
chart.options({
type: 'view',
data, // Shared data (sub-marks can overwrite)
children: [
{ type: 'interval', encode: { x: 'x', y: 'y' } },
{ type: 'line', encode: { x: 'x', y: 'y' } },
{ type: 'text', encode: { x: 'x', y: 'y', text: 'label' } },
],
});
// ✅ When sub-marks need different data, specify data separately in children
chart.options({
type: 'view',
data: mainData,
children: [
{ type: 'interval', encode: { x: 'x', y: 'y' } }, // Use parent mainData
{ type: 'text', data: labelData, encode: { x: 'x', text: 'label' } }, // Use independent data
],
});
// ⚠️ Multiple mark combination rules:
// 1. Only use children, forbidden to use marks, layers and other configurations
// 2. Children cannot be nested (children cannot have children inside)
// 3. Use spaceLayer/spaceFlex for complex combinations
// ❌ Wrong: use marks (forbidden)
chart.options({
type: 'view',
data,
marks: [...], // ❌ Forbidden!
});
// ❌ Wrong: use layers (forbidden)
chart.options({
type: 'view',
data,
Layers: [...], // ❌ Forbidden!
});
// ✅ Correct: use children
chart.options({
type: 'view',
data,
children: [ // ✅ Correct
{ type: 'line', encode: { x: 'year', y: 'value' } },
{ type: 'point', encode: { x: 'year', y: 'value' } },
],
});
// ❌ Wrong: children nesting (forbidden)
chart.options({
type: 'view',
children: [
{
type: 'view',
children: [...], // ❌ Forbidden! Children cannot be nested
},
],
});
// ✅ Correct: use spaceLayer/spaceFlex for complex combinations
chart.options({
type: 'spaceLayer',
children: [
{ type: 'view', children: [...] }, // ✅ Can have view + children under spaceLayer
{ type: 'line', ... },
],
});
// ❌ Wrong: unnecessary scale type specification
chart.options({
scale: {
x: { type: 'linear' }, // ❌ Unnecessary, default is linear
y: { type: 'linear' }, // ❌ Unnecessary
},
});
// ✅ Correct: let G2 infer scale type automatically
chart.options({
scale: {
y: { domain: [0, 100] }, // ✅ Only configure needed properties
},
});3. Basic Structure / 基础结构
3. Basic Structure / Basic Structure
javascript
import { Chart } from '@antv/g2';
const chart = new Chart({ container: 'container', width: 640, height: 480 });
chart.options({
type: 'interval', // Mark type
data: [...], // Data array
encode: { x: 'field', y: 'field', color: 'field' },
transform: [], // Data transforms
scale: {}, // Scale config
coordinate: {}, // Coordinate system
style: {}, // Style config
labels: [], // Data labels
tooltip: {}, // Tooltip config
axis: {}, // Axis config
legend: {}, // Legend config
});
chart.render();javascript
import { Chart } from '@antv/g2';
const chart = new Chart({ container: 'container', width: 640, height: 480 });
chart.options({
type: 'interval', // Mark type
data: [...], // Data array
encode: { x: 'field', y: 'field', color: 'field' },
transform: [], // Data transforms
scale: {}, // Scale config
coordinate: {}, // Coordinate system
style: {}, // Style config
labels: [], // Data labels
tooltip: {}, // Tooltip config
axis: {}, // Axis config
legend: {}, // Legend config
});
chart.render();4. Core / 核心概念
4. Core Concepts / Core Concepts
核心概念是 G2 的基础,理解这些概念是正确使用 G2 的前提。
Core concepts are the foundation of G2, understanding these concepts is a prerequisite for correct use of G2.
4.1 Chart 初始化
4.1 Chart Initialization
Chart 是 G2 的核心类,所有图表都从 Chart 实例开始。
javascript
import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container', // 必填:DOM 容器 ID 或元素
width: 640, // 可选:宽度
height: 480, // 可选:高度
autoFit: true, // 可选:自适应容器大小
padding: 'auto', // 可选:内边距
theme: 'light', // 可选:主题
});详细文档: Chart 初始化
Chart is the core class of G2, all charts start from Chart instances.
javascript
import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container', // Required: DOM container ID or element
width: 640, // Optional: width
height: 480, // Optional: height
autoFit: true, // Optional: auto-fit container size
padding: 'auto', // Optional: padding
theme: 'light', // Optional: theme
});Detailed Documentation: Chart Initialization
4.2 encode 通道系统
4.2 Encode Channel System
encode 将数据字段映射到视觉通道,是 G2 的核心概念。
| 通道 | 用途 | 示例 |
|---|---|---|
| X 轴位置 | |
| Y 轴位置 | |
| 颜色 | |
| 大小 | |
| 形状 | |
详细文档: encode 通道系统
Encode maps data fields to visual channels, which is the core concept of G2.
| Channel | Purpose | Example |
|---|---|---|
| X-axis position | |
| Y-axis position | |
| Color | |
| Size | |
| Shape | |
Detailed Documentation: Encode Channel System
4.3 视图组合 (view + children)
4.3 View Composition (view + children)
使用 类型配合 数组组合多个 mark。
viewchildrenjavascript
chart.options({
type: 'view',
data,
children: [
{ type: 'line', encode: { x: 'date', y: 'value' } },
{ type: 'point', encode: { x: 'date', y: 'value' } },
],
});详细文档: 视图组合
Use type with array to combine multiple marks.
viewchildrenjavascript
chart.options({
type: 'view',
data,
children: [
{ type: 'line', encode: { x: 'date', y: 'value' } },
{ type: 'point', encode: { x: 'date', y: 'value' } },
],
});Detailed Documentation: View Composition
5. Concepts / 概念指南
5. Concept Guides / Concept Guides
概念指南帮助选择正确的图表类型和配置方案。
Concept guides help select the correct chart type and configuration scheme.
5.1 图表类型选择 / Chart Selection
5.1 Chart Selection
根据数据特征和可视化目标选择合适的图表类型:
| 数据关系 | 推荐图表 | Mark |
|---|---|---|
| 比较 | 柱状图、条形图 | |
| 趋势 | 折线图、面积图 | |
| 占比 | 饼图、环形图 | |
| 分布 | 直方图、箱线图 | |
| 相关 | 散点图、气泡图 | |
| 层级 | 矩形树图、旭日图 | |
详细文档: 图表类型选择指南
Select the appropriate chart type based on data characteristics and visualization goals:
| Data Relationship | Recommended Chart | Mark |
|---|---|---|
| Comparison | Bar chart, column chart | |
| Trend | Line chart, area chart | |
| Proportion | Pie chart, donut chart | |
| Distribution | Histogram, box plot | |
| Correlation | Scatter plot, bubble chart | |
| Hierarchy | Treemap, sunburst chart | |
Detailed Documentation: Chart Selection Guide
5.2 视觉通道 / Visual Channels
5.2 Visual Channels
视觉通道是数据到视觉属性的映射方式:
| 通道类型 | 适合数据 | 感知精度 |
|---|---|---|
| 位置 | 连续/离散 | 最高 |
| 长度 | 连续 | 高 |
| 颜色(色相) | 离散 | 中 |
| 颜色(亮度) | 连续 | 中 |
| 大小 | 连续 | 中低 |
| 形状 | 离散 | 低 |
详细文档: 视觉通道
Visual channels are the mapping methods from data to visual attributes:
| Channel Type | Suitable Data | Perception Accuracy |
|---|---|---|
| Position | Continuous/discrete | Highest |
| Length | Continuous | High |
| Color (hue) | Discrete | Medium |
| Color (brightness) | Continuous | Medium |
| Size | Continuous | Medium-low |
| Shape | Discrete | Low |
Detailed Documentation: Visual Channels
5.3 配色理论 / Color Theory
5.3 Color Theory
选择合适的配色方案提升图表可读性:
| 场景 | 推荐方案 | 示例 |
|---|---|---|
| 分类数据 | 离散色板 | |
| 连续数据 | 顺序色板 | |
| 正负对比 | 发散色板 | |
详细文档: 配色理论
Choose the appropriate color scheme to improve chart readability:
| Scenario | Recommended Scheme | Example |
|---|---|---|
| Categorical Data | Discrete color palette | |
| Continuous Data | Sequential color palette | |
| Positive/Negative Comparison | Diverging color palette | |
Detailed Documentation: Color Theory
6. Marks / 图表类型
6. Chart Types / Chart Types
Marks 是 G2 的核心可视化元素,决定了数据的视觉表现形式。每种 Mark 适合特定的数据类型和可视化场景。
Marks are the core visualization elements of G2, determining the visual representation of data. Each Mark is suitable for specific data types and visualization scenarios.
6.1 柱状图系列 / Interval
6.1 Interval Series / Interval
柱状图用于比较分类数据的大小,是最常用的图表类型。基础柱状图使用 mark,堆叠柱状图需要添加 transform,分组柱状图使用 transform。
intervalstackYdodgeX| 类型 | Mark | 关键配置 |
|---|---|---|
| 基础柱状图 | | - |
| 堆叠柱状图 | | |
| 分组柱状图 | | |
| 百分比柱状图 | | |
| 水平柱状图 | | |
详细文档: 基础柱状图 | 堆叠柱状图 | 分组柱状图 | 百分比柱状图
Bar charts are used to compare the size of categorical data, which is the most commonly used chart type. Basic bar charts use mark, stacked bar charts need to add transform, grouped bar charts use transform.
intervalstackYdodgeX| Type | Mark | Key Configuration |
|---|---|---|
| Basic Bar Chart | | - |
| Stacked Bar Chart | | |
| Grouped Bar Chart | | |
| Normalized Bar Chart | | |
| Horizontal Bar Chart | | |
Detailed Documentation: Basic Bar Chart | Stacked Bar Chart | Grouped Bar Chart | Normalized Bar Chart
6.2 折线图系列 / Line
6.2 Line Series / Line
折线图用于展示数据随时间或有序类别的变化趋势。支持单线、多线对比,以及不同插值方式。
| 类型 | Mark | 关键配置 |
|---|---|---|
| 基础折线图 | | - |
| 多系列折线 | | |
| 平滑曲线 | | |
| 阶梯线 | | |
详细文档: 基础折线图 | 多系列折线 | LineX/LineY
Line charts are used to show the change trend of data over time or ordered categories. Support single line, multi-line comparison, and different interpolation methods.
| Type | Mark | Key Configuration |
|---|---|---|
| Basic Line Chart | | - |
| Multi-series Line Chart | | |
| Smooth Curve | | |
| Step Line | | |
Detailed Documentation: Basic Line Chart | Multi-series Line Chart | LineX/LineY
6.3 面积图系列 / Area
6.3 Area Series / Area
面积图在折线图基础上填充区域,强调数量随时间的变化程度。堆叠面积图用于展示各部分对整体的贡献。
| 类型 | Mark | 关键配置 |
|---|---|---|
| 基础面积图 | | - |
| 堆叠面积图 | | |
详细文档: 基础面积图 | 堆叠面积图
Area charts fill the area below the line chart, emphasizing the degree of change in quantity over time. Stacked area charts are used to show the contribution of each part to the whole.
| Type | Mark | Key Configuration |
|---|---|---|
| Basic Area Chart | | - |
| Stacked Area Chart | | |
Detailed Documentation: Basic Area Chart | Stacked Area Chart
6.4 饼图/环形图 / Arc (Pie/Donut)
6.4 Pie/Donut Chart / Arc (Pie/Donut)
饼图用于展示各部分占整体的比例关系。使用 坐标系配合 mark 实现。
thetainterval| 类型 | Mark | 关键配置 |
|---|---|---|
| 饼图 | | |
| 环形图 | | |
详细文档: 饼图 | 环形图
Pie charts are used to show the proportional relationship of each part to the whole. Implemented using coordinate system with mark.
thetainterval| Type | Mark | Key Configuration |
|---|---|---|
| Pie Chart | | |
| Donut Chart | | |
Detailed Documentation: Pie Chart | Donut Chart
6.5 散点图/气泡图 / Point
6.5 Scatter/Bubble Chart / Point
散点图用于展示两个数值变量的关系,气泡图通过点的大小展示第三个维度。
| 类型 | Mark | 关键配置 |
|---|---|---|
| 散点图 | | |
| 气泡图 | | |
详细文档: 散点图 | 气泡图
Scatter plots are used to show the relationship between two numerical variables, bubble charts show a third dimension through the size of points.
| Type | Mark | Key Configuration |
|---|---|---|
| Scatter Plot | | |
| Bubble Chart | | |
Detailed Documentation: Scatter Plot | Bubble Chart
6.6 直方图 / Histogram
6.6 Histogram / Histogram
直方图用于展示连续数值数据的分布情况,使用 标记配合 转换实现。与柱状图不同,直方图的柱子之间无间隔,表示数据连续。
rectbinX| 类型 | Mark | 关键配置 |
|---|---|---|
| 基础直方图 | | |
| 多分布对比 | | |
详细文档: 直方图
Histograms are used to show the distribution of continuous numerical data, implemented using mark with transform. Different from bar charts, there are no gaps between the bars of histograms, indicating continuous data.
rectbinX| Type | Mark | Key Configuration |
|---|---|---|
| Basic Histogram | | |
| Multi-distribution Comparison | | |
Detailed Documentation: Histogram
6.7 玫瑰图/玉珏图 / Polar Charts
6.7 Rose/Radial Bar Chart / Polar Charts
极坐标系下的图表,通过半径或弧长表示数值大小,视觉上更加美观。
| 类型 | Mark | 关键配置 |
|---|---|---|
| 玫瑰图 | | |
| 玉珏图 | | |
详细文档: 玫瑰图 | 玉珏图
Charts in polar coordinate system, representing numerical size through radius or arc length, which are more visually appealing.
| Type | Mark | Key Configuration |
|---|---|---|
| Rose Chart | | |
| Radial Bar Chart | | |
Detailed Documentation: Rose Chart | Radial Bar Chart
6.8 统计分布图 / Distribution
6.8 Statistical Distribution Charts / Distribution
展示数据分布特征的图表,适用于统计分析和探索性数据分析。
| 类型 | Mark | 用途 |
|---|---|---|
| 箱线图 | | 数据分布统计 |
| 箱型图(Box) | | 手动指定五数概括的箱线图 |
| 密度图 | | 核密度估计曲线 |
| 小提琴图 | | 密度分布 + 统计信息 |
| 多边形 | | 自定义多边形区域 |
详细文档: 箱线图 | 箱型图(Box) | 密度图 | 小提琴图 | 多边形
Charts showing data distribution characteristics, suitable for statistical analysis and exploratory data analysis.
| Type | Mark | Purpose |
|---|---|---|
| Box Plot | | Data distribution statistics |
| Custom Box Plot | | Box plot with manually specified five-number summary |
| Density Plot | | Kernel density estimation curve |
| Violin Plot | | Density distribution + statistical information |
| Polygon | | Custom polygon area |
Detailed Documentation: Box Plot | Custom Box Plot | Density Plot | Violin Plot | Polygon
6.9 关系图 / Relation
6.9 Relationship Charts / Relation
展示数据之间关系的图表,适用于网络分析和集合关系展示。
| 类型 | Mark | 用途 |
|---|---|---|
| 桑基图 | | 流向/转移关系 |
| 和弦图 | | 矩阵流向关系 |
| 韦恩图 | | 集合交集关系(venn 是 data transform,不是 mark type) |
| 弧长连接图 | | 节点链接关系 |
详细文档: 桑基图 | 和弦图 | 韦恩图 | 弧长连接图
Charts showing relationships between data, suitable for network analysis and set relationship display.
| Type | Mark | Purpose |
|---|---|---|
| Sankey Diagram | | Flow/transfer relationship |
| Chord Diagram | | Matrix flow relationship |
| Venn Diagram | | Set intersection relationship (venn is data transform, not mark type) |
| Arc Diagram | | Node link relationship |
Detailed Documentation: Sankey Diagram | Chord Diagram | Venn Diagram | Arc Diagram
6.10 项目管理图 / Project
6.10 Project Management Charts / Project
适用于项目管理和进度跟踪的图表。
| 类型 | Mark | 用途 |
|---|---|---|
| 甘特图 | | 任务时间安排 |
| 子弹图 | | KPI 指标展示 |
详细文档: 甘特图 | 子弹图
Charts suitable for project management and progress tracking.
| Type | Mark | Purpose |
|---|---|---|
| Gantt Chart | | Task schedule |
| Bullet Chart | | KPI indicator display |
Detailed Documentation: Gantt Chart | Bullet Chart
6.11 金融图表 / Finance
6.11 Financial Charts / Finance
适用于金融数据分析的专业图表。
| 类型 | Mark | 用途 |
|---|---|---|
| K线图 | | 股票四价数据 |
详细文档: K线图
Professional charts suitable for financial data analysis.
| Type | Mark | Purpose |
|---|---|---|
| K-line Chart | | Stock four-price data |
Detailed Documentation: K-line Chart
6.12 多维数据图 / Multivariate
6.12 Multivariate Data Charts / Multivariate
展示多维数据关系的图表。
| 类型 | Mark | 用途 |
|---|---|---|
| 平行坐标系 | | 多维数据关系分析 |
| 雷达图 | | 多维数据对比 |
详细文档: 平行坐标系 | 雷达图
Charts showing relationships between multivariate data.
| Type | Mark | Purpose |
|---|---|---|
| Parallel Coordinates | | Multivariate data relationship analysis |
| Radar Chart | | Multivariate data comparison |
Detailed Documentation: Parallel Coordinates | Radar Chart
6.13 对比图 / Comparison
6.13 Comparison Charts / Comparison
适用于数据对比的图表。
| 类型 | Mark | 用途 |
|---|---|---|
| 双向柱状图 | | 正负数据对比 |
详细文档: 双向柱状图
Charts suitable for data comparison.
| Type | Mark | Purpose |
|---|---|---|
| Bi-directional Bar Chart | | Positive/negative data comparison |
Detailed Documentation: Bi-directional Bar Chart
6.14 基础标记 / Basic Marks
6.14 Basic Marks / Basic Marks
基础标记是 G2 的底层构建块,可独立使用或组合构建复杂图表。
| 类型 | Mark | 用途 |
|---|---|---|
| 矩形 | | 矩形区域,直方图/热力图基础 |
| 文本 | | 文本标注和标签 |
| 图片 | | 图片标记,数据点用图片表示 |
| 路径 | | 自定义路径绘制 |
| 链接 | | 两点之间的连线 |
| 连接器 | | 数据点之间的连接线 |
| 形状 | | 自定义形状绘制 |
| 向量 | | 向量/箭头标记,风场图等 |
详细文档: rect | text | image | path | link | connector | shape | vector
Basic marks are the underlying building blocks of G2, which can be used independently or combined to build complex charts.
| Type | Mark | Purpose |
|---|---|---|
| Rectangle | | Rectangular area, foundation of histogram/heatmap |
| Text | | Text annotation and labels |
| Image | | Image mark, data points represented by images |
| Path | | Custom path drawing |
| Link | | Line between two points |
| Connector | | Connection line between data points |
| Shape | | Custom shape drawing |
| Vector | | Vector/arrow mark, used for wind field charts etc. |
Detailed Documentation: rect | text | image | path | link | connector | shape | vector
6.15 范围标记 / Range
6.15 Range Marks / Range
范围标记用于展示数据的区间范围。
| 类型 | Mark | 用途 |
|---|---|---|
| 时间段/区间高亮(X 方向) | | X 轴区间, |
| 数值范围高亮(Y 方向) | | Y 轴区间, |
| 二维矩形区域 | | x/y 字段为 |
详细文档: range/rangeY | rangeX
Range marks are used to show the interval range of data.
| Type | Mark | Purpose |
|---|---|---|
| Time period/interval highlight (X direction) | | X-axis interval, |
| Value range highlight (Y direction) | | Y-axis interval, |
| 2D rectangular area | | x/y fields are |
Detailed Documentation: range/rangeY | rangeX
6.16 分布与打包图 / Distribution & Pack
6.16 Distribution & Pack Charts / Distribution & Pack
| 类型 | Mark | 用途 |
|---|---|---|
| 蜂群图 | | 数据点紧密排列展示分布 |
| 打包图 | | 层级数据的圆形打包 |
详细文档: 蜂群图 | 打包图
| Type | Mark | Purpose |
|---|---|---|
| Beeswarm Plot | | Data points are closely arranged to show distribution |
| Pack Chart | | Circular packing of hierarchical data |
Detailed Documentation: Beeswarm Plot | Pack Chart
6.17 层次结构图 / Hierarchy
6.17 Hierarchy Charts / Hierarchy
展示层级数据的图表,通过面积或半径表示数值占比。
| 类型 | Mark | 用途 |
|---|---|---|
| 矩形树图 | | 层级数据占比 |
| 旭日图 | | 多层级同心圆展示(需引入 @antv/g2-extension-plot) |
| 分区图 | | 层级数据分区展示 |
| 树图 | | 树形层级结构 |
详细文档: 矩形树图 | 旭日图 | 分区图 | 树图
Charts showing hierarchical data, representing the proportion of values through area or radius.
| Type | Mark | Purpose |
|---|---|---|
| Treemap | | Hierarchical data proportion |
| Sunburst Chart | | Multi-level concentric circle display (requires @antv/g2-extension-plot) |
| Partition Chart | | Hierarchical data partition display |
| Tree Diagram | | Tree hierarchical structure |
Detailed Documentation: Treemap | Sunburst Chart | Partition Chart | Tree Diagram
6.18 其他图表 / Others
6.18 Other Charts / Others
| 类型 | Mark | 用途 |
|---|---|---|
| 热力图 | | 二维矩阵数据可视化 |
| 密度热力图 | | 连续密度热力图 |
| 仪表盘 | | 指标进度展示 |
| 词云 | | 文本频率可视化 |
| 水波图 | | 百分比进度 |
详细文档: 热力图 | 密度热力图 | 仪表盘 | 词云 | 水波图
| Type | Mark | Purpose |
|---|---|---|
| Heatmap | | 2D matrix data visualization |
| Density Heatmap | | Continuous density heatmap |
| Gauge | | Indicator progress display |
| Word Cloud | | Text frequency visualization |
| Liquid Fill Chart | | Percentage progress |
Detailed Documentation: Heatmap | Density Heatmap | Gauge | Word Cloud | Liquid Fill Chart
7. Data / 数据变换
7. Data Transforms / Data Transforms
数据变换在数据加载阶段执行,配置在 中,影响所有使用该数据的标记。
data.transformData transforms are executed during data loading phase, configured in , affecting all marks using this data.
data.transform7.1 Data Transform 类型(配置在 data.transform
)
data.transform7.1 Data Transform Types (configured in data.transform
)
data.transform| 变换 | 类型 | 用途 | 示例场景 |
|---|---|---|---|
| fold | | 宽表转长表 | 多列数据转多系列 |
| filter | | 条件过滤数据 | 过滤无效数据 |
| sort | | 使用回调函数排序 | 自定义排序逻辑 |
| sortBy | | 按字段排序 | 按字段值排序 |
| map | | 数据映射转换 | 添加计算字段 |
| join | | 合并数据表 | 关联外部数据 |
| pick | | 选择指定字段 | 精简字段 |
| rename | | 重命名字段 | 字段重命名 |
| slice | | 截取数据范围 | 分页/截取 |
| ema | | 指数移动平均 | 时间序列平滑 |
| kde | | 核密度估计 | 密度图/小提琴图 |
| log | | 打印数据到控制台 | 调试 |
| custom | | 自定义数据处理 | 复杂转换 |
| Transform | Type | Purpose | Example Scenario |
|---|---|---|---|
| fold | | Wide to long table | Convert multi-column data to multi-series |
| filter | | Conditional data filtering | Filter invalid data |
| sort | | Sort using callback function | Custom sorting logic |
| sortBy | | Sort by field | Sort by field value |
| map | | Data mapping transformation | Add calculated fields |
| join | | Merge data tables | Associate external data |
| pick | | Select specified fields | Simplify fields |
| rename | | Rename fields | Field renaming |
| slice | | Intercept data range | Pagination/interception |
| ema | | Exponential moving average | Time series smoothing |
| kde | | Kernel density estimation | Density plot/violin plot |
| log | | Print data to console | Debugging |
| custom | | Custom data processing | Complex transformation |
7.2 数据格式与模式
7.2 Data Format and Patterns
| 类型 | 用途 |
|---|---|
| 表格数据格式 | G2 接受的标准表格数据格式说明 |
| 数据变换模式 | Data Transform 和 Mark Transform 的组合使用模式 |
详细文档: filter | sort | sortBy | fold | slice | ema | kde | log | fetch | 表格数据格式 | 数据变换模式
| Type | Purpose |
|---|---|
| Tabular Data Format | Description of standard tabular data format accepted by G2 |
| Data Transform Patterns | Combined usage patterns of Data Transform and Mark Transform |
Detailed Documentation: filter | sort | sortBy | fold | slice | ema | kde | log | fetch | Tabular Data Format | Data Transform Patterns
7.3 常见错误:Data Transform 放错位置
7.3 Common Mistake: Wrong Placement of Data Transform
javascript
// ❌ 错误:fold 是数据变换,不能放在 mark transform
chart.options({
type: 'interval',
data: wideData,
transform: [{ type: 'fold', fields: ['a', 'b'] }], // ❌ 错误!
});
// ✅ 正确:fold 放在 data.transform
chart.options({
type: 'interval',
data: {
type: 'inline',
value: wideData,
transform: [{ type: 'fold', fields: ['a', 'b'] }], // ✅ 正确
},
transform: [{ type: 'stackY' }], // mark transform
});javascript
// ❌ Wrong: fold is data transform, cannot be placed in mark transform
chart.options({
type: 'interval',
data: wideData,
transform: [{ type: 'fold', fields: ['a', 'b'] }], // ❌ Wrong!
});
// ✅ Correct: fold is placed in data.transform
chart.options({
type: 'interval',
data: {
type: 'inline',
value: wideData,
transform: [{ type: 'fold', fields: ['a', 'b'] }], // ✅ Correct
},
transform: [{ type: 'stackY' }], // mark transform
});7.4 组合示例:宽表数据 + 堆叠图
7.4 Combination Example: Wide Table Data + Stacked Chart
javascript
// 宽表数据:每个月有多个类型的数据列
const wideData = [
{ year: '2000', '类型 A': 21, '类型 B': 16, '类型 C': 8 },
{ year: '2001', '类型 A': 25, '类型 B': 16, '类型 C': 8 },
// ...
];
chart.options({
type: 'interval',
data: {
type: 'inline',
value: wideData,
transform: [
// ✅ Data Transform:宽表转长表
{ type: 'fold', fields: ['类型 A', '类型 B', '类型 C'], key: 'type', value: 'value' },
],
},
encode: { x: 'year', y: 'value', color: 'type' },
transform: [
// ✅ Mark Transform:堆叠
{ type: 'stackY' },
],
coordinate: { type: 'polar' }, // 极坐标系
});javascript
// Wide table data: each month has multiple type data columns
const wideData = [
{ year: '2000', 'Type A': 21, 'Type B': 16, 'Type C': 8 },
{ year: '2001', 'Type A': 25, 'Type B': 16, 'Type C': 8 },
// ...
];
chart.options({
type: 'interval',
data: {
type: 'inline',
value: wideData,
transform: [
// ✅ Data Transform: wide to long table
{ type: 'fold', fields: ['Type A', 'Type B', 'Type C'], key: 'type', value: 'value' },
],
},
encode: { x: 'year', y: 'value', color: 'type' },
transform: [
// ✅ Mark Transform: stack
{ type: 'stackY' },
],
coordinate: { type: 'polar' }, // Polar coordinate system
});8. Transforms / 标记变换
8. Mark Transforms / Mark Transforms
标记变换在绑定视觉通道时执行,配置在 mark 的 数组中,用于数据聚合、防重叠等。
transform配置位置: 数组,与 、 同级,不是在 中。
transformdataencodedata.transformjavascript
chart.options({
type: 'interval',
data,
encode: { x: 'category', y: 'value', color: 'type' },
transform: [ // ✅ Mark Transform:与 data/encode 同级
{ type: 'stackY' },
{ type: 'sortX', by: 'y' },
],
});Mark transforms are executed when binding visual channels, configured in the array of the mark, used for data aggregation, anti-overlap, etc.
transformConfiguration Position: array, at the same level as and , not in .
transformdataencodedata.transformjavascript
chart.options({
type: 'interval',
data,
encode: { x: 'category', y: 'value', color: 'type' },
transform: [ // ✅ Mark Transform: same level as data/encode
{ type: 'stackY' },
{ type: 'sortX', by: 'y' },
],
});8.1 防重叠变换 / Anti-overlap
8.1 Anti-overlap Transforms / Anti-overlap
| 变换 | 类型 | 用途 |
|---|---|---|
| 堆叠 | | 数据堆叠,用于堆叠图 |
| 分组 | | 数据分组,用于分组图 |
| 抖动 | | 散点抖动避免重叠 |
| X轴抖动 | | X 方向抖动 |
| Y轴抖动 | | Y 方向抖动 |
| 打包 | | 紧密排列数据点 |
详细文档: stackY | dodgeX | jitter | jitterX | jitterY | pack
| Transform | Type | Purpose |
|---|---|---|
| Stack | | Data stacking, used for stacked charts |
| Dodge | | Data grouping, used for grouped charts |
| Jitter | | Scatter jitter to avoid overlap |
| Jitter X | | X direction jitter |
| Jitter Y | | Y direction jitter |
| Pack | | Closely arrange data points |
Detailed Documentation: stackY | dodgeX | jitter | jitterX | jitterY | pack
8.2 聚合变换 / Aggregation
8.2 Aggregation Transforms / Aggregation
| 变换 | 类型 | 用途 |
|---|---|---|
| 通用分组 | | 通用分组聚合 |
| 分组聚合 | | 按维度分组并聚合 |
| 分组颜色 | | 按颜色分组聚合 |
| 分箱 | | 二维分箱 |
| X轴分箱 | | X 轴方向分箱 |
| 采样 | | 数据采样 |
详细文档: group | groupX | groupY | groupColor | bin | binX | sample
| Transform | Type | Purpose |
|---|---|---|
| General Group | | General grouping aggregation |
| Group by X | | Group by dimension and aggregate |
| Group by Color | | Group by color and aggregate |
| Bin | | 2D binning |
| Bin X | | X direction binning |
| Sample | | Data sampling |
Detailed Documentation: group | groupX | groupY | groupColor | bin | binX | sample
8.3 排序变换 / Sorting
8.3 Sorting Transforms / Sorting
| 变换 | 类型 | 用途 |
|---|---|---|
| X轴排序 | | 按 X 通道排序 |
| Y轴排序 | | 按 Y 通道排序 |
| 颜色排序 | | 按颜色通道排序 |
详细文档: sortX | sortY | sortColor
| Transform | Type | Purpose |
|---|---|---|
| Sort X | | Sort by X channel |
| Sort Y | | Sort by Y channel |
| Sort Color | | Sort by color channel |
Detailed Documentation: sortX | sortY | sortColor
8.4 选取变换 / Selection
8.4 Selection Transforms / Selection
| 变换 | 类型 | 用途 |
|---|---|---|
| 选取 | | 全局选取数据 |
| X轴选取 | | 按 X 分组选取 |
| Y轴选取 | | 按 Y 分组选取 |
详细文档: select | selectX | selectY
| Transform | Type | Purpose |
|---|---|---|
| Select | | Global data selection |
| Select X | | Select by X grouping |
| Select Y | | Select by Y grouping |
Detailed Documentation: select | selectX | selectY
8.5 其他变换 / Others
8.5 Other Transforms / Others
| 变换 | 类型 | 用途 |
|---|---|---|
| 归一化 | | Y 轴归一化 |
| 差值 | | 计算差值 |
| 对称 | | Y 轴对称 |
| 弹性X | | X 轴弹性布局 |
| 堆叠入场 | | 入场动画堆叠 |
详细文档: normalizeY | diffY | symmetryY | flexX | stackEnter
| Transform | Type | Purpose |
|---|---|---|
| Normalize | | Y-axis normalization |
| Diff | | Calculate difference |
| Symmetry | | Y-axis symmetry |
| Flex X | | X-axis flexible layout |
| Stack Enter | | Stacked enter animation |
Detailed Documentation: normalizeY | diffY | symmetryY | flexX | stackEnter
9. Interactions / 交互
9. Interactions / Interactions
G2 提供丰富的内置交互,用于数据探索和图表操作。
G2 provides rich built-in interactions for data exploration and chart operation.
9.1 选择类交互 / Selection
9.1 Selection Interactions / Selection
| 交互 | 类型 | 用途 |
|---|---|---|
| 元素选择 | | 点击选择数据元素 |
| 按条件选择 | | 按条件批量选择元素 |
| 框选 | | 矩形区域选择 |
| 二维框选 | | XY 同时框选 |
| 轴框选 | | 坐标轴范围选择 |
| 图例过滤 | | 点击图例筛选数据 |
详细文档: elementSelect | elementSelectBy | brush | brushXY | brushAxis | legendFilter
| Interaction | Type | Purpose |
|---|---|---|
| Element Select | | Click to select data elements |
| Element Select By | | Batch select elements by condition |
| Brush / Brush X / Brush Y | | Rectangular area selection |
| Brush XY | | XY simultaneous selection |
| Brush Axis | | Coordinate axis range selection |
| Legend Filter | | Click legend to filter data |
Detailed Documentation: elementSelect | elementSelectBy | brush | brushXY | brushAxis | legendFilter
9.2 高亮类交互 / Highlight
9.2 Highlight Interactions / Highlight
| 交互 | 类型 | 用途 |
|---|---|---|
| 元素高亮 | | 悬停高亮元素 |
| 按条件高亮 | | 按条件批量高亮元素 |
| 悬停缩放 | | 悬停时元素放大 |
| 图例高亮 | | 悬停图例高亮对应元素 |
| 框选高亮 | | 框选区域高亮 |
详细文档: elementHighlight | elementHighlightBy | elementHoverScale | legendHighlight | brushXHighlight | brushYHighlight | 单轴框选高亮
| Interaction | Type | Purpose |
|---|---|---|
| Element Highlight | | Hover to highlight elements |
| Element Highlight By | | Batch highlight elements by condition |
| Element Hover Scale | | Element scales up on hover |
| Legend Highlight | | Hover legend to highlight corresponding elements |
| Brush X Highlight / Brush Y Highlight | | Highlight brush area |
Detailed Documentation: elementHighlight | elementHighlightBy | elementHoverScale | legendHighlight | brushXHighlight | brushYHighlight | Single Axis Brush Highlight
9.3 过滤类交互 / Filter
9.3 Filter Interactions / Filter
| 交互 | 类型 | 用途 |
|---|---|---|
| 滑动条过滤 | | 滑动条筛选数据范围 |
| 滚动条过滤 | | 滚动条筛选数据 |
| 框选过滤 | | 框选区域过滤数据 |
| X轴框选过滤 | | X 轴方向框选过滤 |
| Y轴框选过滤 | | Y 轴方向框选过滤 |
| 自适应过滤 | | 自适应数据过滤 |
详细文档: sliderFilter | scrollbarFilter | brushFilter | brushXFilter | brushYFilter | adaptiveFilter
| Interaction | Type | Purpose |
|---|---|---|
| Slider Filter | | Slider to filter data range |
| Scrollbar Filter | | Scrollbar to filter data |
| Brush Filter | | Brush area to filter data |
| Brush X Filter | | X direction brush to filter data |
| Brush Y Filter | | Y direction brush to filter data |
| Adaptive Filter | | Adaptive data filtering |
Detailed Documentation: sliderFilter | scrollbarFilter | brushFilter | brushXFilter | brushYFilter | adaptiveFilter
9.4 其他交互 / Others
9.4 Other Interactions / Others
| 交互 | 类型 | 用途 |
|---|---|---|
| 提示信息 | | 悬停显示数据详情 |
| 气泡提示 | | 简洁气泡提示 |
| 下钻 | | 层级数据下钻 |
| 矩形树图下钻 | | 矩形树图层级下钻 |
| 缩放 | | 鱼眼放大镜效果 |
| 滚轮滑动 | | 鼠标滚轮控制滑动条 |
| 拖拽移动 | | 拖拽数据点移动 |
| 图表索引 | | 多图表联动索引线 |
详细文档: tooltip | poptip | drilldown | treemapDrilldown | fisheye | sliderWheel | elementPointMove | chartIndex
| Interaction | Type | Purpose |
|---|---|---|
| Tooltip | | Hover to show data details |
| Poptip | | Concise poptip |
| Drilldown | | Hierarchical data drilldown |
| Treemap Drilldown | | Treemap hierarchical drilldown |
| Fisheye | | Fisheye magnifier effect |
| Slider Wheel | | Mouse wheel controls slider |
| Element Point Move | | Drag data points to move |
| Chart Index | | Multi-chart linkage index line |
Detailed Documentation: tooltip | poptip | drilldown | treemapDrilldown | fisheye | sliderWheel | elementPointMove | chartIndex
10. Components / 组件
10. Components / Components
组件是图表的辅助元素,如坐标轴、图例、提示信息等。
Components are auxiliary elements of charts, such as axes, legends, tooltips, etc.
10.1 坐标轴 / Axis
10.1 Axis / Axis
坐标轴展示数据维度,支持丰富的样式配置。
详细文档: 坐标轴配置 | 雷达图坐标轴
Axes display data dimensions, supporting rich style configurations.
Detailed Documentation: Axis Configuration | Radar Chart Axis
10.2 图例 / Legend
10.2 Legend / Legend
图例展示数据分类或连续数值映射,支持分类图例和连续图例(色带)。
| 类型 | 用途 |
|---|---|
| 分类图例 | 离散分类数据的颜色映射说明 |
| 连续图例 | 连续数值的颜色/大小映射说明(色带) |
详细文档: 图例配置 | 分类图例 | 连续图例
Legends display data category or continuous value mapping, supporting category legends and continuous legends (color bands).
| Type | Purpose |
|---|---|
| Category Legend | Color mapping description of discrete categorical data |
| Continuous Legend | Color/size mapping description of continuous values (color band) |
Detailed Documentation: Legend Configuration | Category Legend | Continuous Legend
10.3 提示信息 / Tooltip
10.3 Tooltip / Tooltip
Tooltip 在悬停时显示数据详情,支持自定义模板和格式化。
详细文档: Tooltip 配置
Tooltip shows data details on hover, supporting custom templates and formatting.
Detailed Documentation: Tooltip Configuration
10.4 其他组件 / Others
10.4 Other Components / Others
| 组件 | 用途 |
|---|---|
| 标题 | 图表标题 |
| 标签 | 数据标签 |
| 滚动条 | 数据滚动浏览 |
| 滑动条 | 数据范围选择 |
| 标注 | 数据标注和辅助线 |
详细文档: 标题 | 标签 | 滚动条 | 滑动条 | 标注
| Component | Purpose |
|---|---|
| Title | Chart title |
| Label | Data label |
| Scrollbar | Data scroll browsing |
| Slider | Data range selection |
| Annotation | Data annotation and auxiliary lines |
Detailed Documentation: Title | Label | Scrollbar | Slider | Annotation
11. Scales / 比例尺
11. Scales / Scales
比例尺将数据值映射到视觉通道,如位置、颜色、大小等。
Scales map data values to visual channels, such as position, color, size, etc.
11.1 ⚠️ 默认行为(不要过度指定 type)
11.1 ⚠️ Default Behavior (Do not over-specify type)
G2 会根据数据类型自动推断 scale 类型,非特殊情况下不要手动指定 type:
| 数据类型 | 自动推断的 scale | 示例 |
|---|---|---|
| 数值字段 | | |
| 分类字段 | | |
| Date 对象 | | |
javascript
// ❌ 错误:不必要的 type 指定,可能导致渲染异常
chart.options({
scale: {
x: { type: 'linear' }, // ❌ 数值字段默认就是 linear
y: { type: 'linear' }, // ❌ 不需要指定
},
});
// ✅ 正确:让 G2 自动推断,只在需要时配置 domain/range
chart.options({
scale: {
y: { domain: [0, 100] }, // ✅ 只配置需要的属性
color: { range: ['#1890ff', '#52c41a'] },
},
});需要手动指定 type 的特殊情况:
| 场景 | type | 说明 |
|---|---|---|
| 对数刻度 | | 跨数量级数据 |
| 幂函数刻度 | | 非线性数据映射 |
| 平方根刻度 | | 非负数据的压缩 |
| 字符串日期 | | 日期字段是字符串而非 Date 对象时 |
| 自定义映射 | | 离散值到离散值 |
| 渐变色 | | 连续数值到颜色渐变 |
| 分段映射 | | 按阈值分段映射到颜色 |
| 等量分段 | | 连续数据离散化 |
G2 automatically infers scale type based on data type, do not manually specify type unless necessary:
| Data Type | Automatically Inferred Scale | Example |
|---|---|---|
| Numeric Field | | |
| Categorical Field | | |
| Date Object | | |
javascript
// ❌ Wrong: unnecessary type specification, may cause rendering exceptions
chart.options({
scale: {
x: { type: 'linear' }, // ❌ Numeric fields are linear by default
y: { type: 'linear' }, // ❌ No need to specify
},
});
// ✅ Correct: let G2 infer automatically, only configure domain/range when needed
chart.options({
scale: {
y: { domain: [0, 100] }, // ✅ Only configure needed properties
color: { range: ['#1890ff', '#52c41a'] },
},
});Special cases where type needs to be manually specified:
| Scenario | type | Description |
|---|---|---|
| Logarithmic Scale | | Cross-order-of-magnitude data |
| Power Scale | | Non-linear data mapping |
| Square Root Scale | | Compression of non-negative data |
| String Date | | When date field is string instead of Date object |
| Custom Mapping | | Discrete to discrete mapping |
| Gradient Color | | Continuous value to color gradient |
| Threshold Mapping | | Segment mapping to color by threshold |
| Equal Quantization | | Discretization of continuous data |
11.2 比例尺类型
11.2 Scale Types
| 比例尺 | 类型 | 用途 |
|---|---|---|
| 线性 | | 连续数值映射(默认) |
| 分类 | | 离散分类映射(默认) |
| 点 | | 离散点位置映射 |
| 时间 | | 时间数据映射 |
| 对数 | | 对数刻度 |
| 幂/平方根 | | 幂函数/平方根映射 |
| 序数 | | 离散值到离散值映射 |
| 顺序 | | 连续值到颜色渐变 |
| 分位数/量化 | | 连续数据离散化映射 |
| 阈值 | | 按阈值分段映射 |
详细文档: linear | band | point | time | log | pow/sqrt | ordinal | sequential | quantile/quantize | threshold
| Scale | Type | Purpose |
|---|---|---|
| Linear | | Continuous numeric mapping (default) |
| Band | | Discrete categorical mapping (default) |
| Point | | Discrete point position mapping |
| Time | | Time data mapping |
| Log | | Logarithmic scale |
| Power / Square Root | | Power function/square root mapping |
| Ordinal | | Discrete to discrete mapping |
| Sequential | | Continuous value to color gradient |
| Quantile / Quantize | | Discretization mapping of continuous data |
| Threshold | | Segment mapping by threshold |
Detailed Documentation: linear | band | point | time | log | pow/sqrt | ordinal | sequential | quantile/quantize | threshold
12. Coordinates / 坐标系
12. Coordinates / Coordinates
坐标系定义数据到画布位置的映射方式,不同坐标系产生不同图表形态。
| 坐标系 | 类型 | 用途 |
|---|---|---|
| 笛卡尔 | | 直角坐标系(默认) |
| 极坐标 | | 雷达图、玫瑰图 |
| Theta | | 饼图、环形图 |
| 径向 | | 径向坐标系,玉珏图 |
| 转置 | | X/Y 轴交换 |
| 平行 | | 平行坐标系 |
| 螺旋 | | 螺旋坐标系 |
| 鱼眼 | | 局部放大效果 |
详细文档: cartesian | polar | theta | radial | transpose | parallel | helix | fisheye
Coordinate systems define the mapping from data to canvas positions, different coordinate systems produce different chart forms.
| Coordinate System | Type | Purpose |
|---|---|---|
| Cartesian | | Rectangular coordinate system (default) |
| Polar | | Radar chart, rose chart |
| Theta | | Pie chart, donut chart |
| Radial | | Radial coordinate system, radial bar chart |
| Transpose | | X/Y axis swap |
| Parallel | | Parallel coordinate system |
| Helix | | Helix coordinate system |
| Fisheye | | Local magnification effect |
Detailed Documentation: cartesian | polar | theta | radial | transpose | parallel | helix | fisheye
13. Compositions / 组合视图
13. View Compositions / View Compositions
组合视图用于创建多图表布局,如分面、多视图叠加等。
| 组合 | 类型 | 用途 |
|---|---|---|
| 基础视图 | | 单视图容器,组合多个 mark |
| 分面图 | | 按维度拆分矩形网格多图 |
| 圆形分面 | | 按维度拆分环形多图 |
| 重复矩阵 | | 多变量组合矩阵图 |
| 空间层叠 | | 多图层叠加 |
| 空间弹性 | | 弹性布局 |
| 时间关键帧 | | 动画序列 |
| 地理视图 | | 地理坐标系视图 |
| 地图 | | 地理路径绘制 |
详细文档: view | facetRect | facetCircle | repeatMatrix | spaceLayer | spaceFlex | timingKeyframe | geoView | 地图
View compositions are used to create multi-chart layouts, such as facets, multi-view overlays, etc.
| Composition | Type | Purpose |
|---|---|---|
| Basic View | | Single view container, combining multiple marks |
| Facet Rect | | Split into rectangular grid multi-charts by dimension |
| Facet Circle | | Split into circular multi-charts by dimension |
| Repeat Matrix | | Multi-variable combination matrix chart |
| Space Layer | | Multi-layer overlay |
| Space Flex | | Flexible layout |
| Timing Keyframe | | Animation sequence |
| Geo View | | Geographic coordinate system view |
| Map | | Geographic path drawing |
Detailed Documentation: view | facetRect | facetCircle | repeatMatrix | spaceLayer | spaceFlex | timingKeyframe | geoView | Map
14. Themes / 主题
14. Themes / Themes
主题定义图表的整体视觉风格,包括颜色、字体、间距等。
详细文档: 内置主题 | 自定义主题
Themes define the overall visual style of charts, including colors, fonts, spacing, etc.
Detailed Documentation: Built-in Themes | Custom Themes
15. Palettes / 调色板
15. Palettes / Palettes
调色板定义颜色序列,用于分类数据或连续数据的颜色映射。
详细文档: category10 | category20
Palettes define color sequences for color mapping of categorical or continuous data.
Detailed Documentation: category10 | category20
16. Animations / 动画
16. Animations / Animations
动画增强图表的表现力,支持入场、更新、退场动画配置。
⚠️ 重要规则:G2 底层自带默认动画效果,用户没有明确要求动画时不要添加 配置。只有用户明确描述了动画需求(如"渐入动画"、"波浪入场"等)时,才查阅参考文档添加对应的 animate 配置。
animate详细文档: 动画介绍 | 动画类型 | 关键帧动画
Animations enhance the expressiveness of charts, supporting entry, update, and exit animation configurations.
⚠️ Important Rule: G2 has built-in default animation effects at the bottom level, do not add configuration when users do not explicitly request animation. Only add the corresponding animate configuration when users clearly describe animation requirements (such as "fade-in animation", "wave entry", etc.) by referring to the documentation.
animateDetailed Documentation: Animation Introduction | Animation Types | Keyframe Animation
17. Label Transforms / 标签变换
17. Label Transforms / Label Transforms
标签变换用于处理标签重叠、溢出等问题,提升标签可读性。
| 变换 | 类型 | 用途 |
|---|---|---|
| 溢出隐藏 | | 超出区域的标签隐藏 |
| 重叠隐藏 | | 重叠标签自动隐藏 |
| 重叠偏移 | | 重叠标签 Y 方向偏移 |
| 对比反转 | | 标签颜色自动反转以保证对比度 |
| 溢出调整 | | 超出画布边界的标签位置调整 |
| 溢出描边 | | 溢出区域添加描边标记 |
详细文档: overflowHide | overlapHide | overlapDodgeY | contrastReverse | exceedAdjust | overflowStroke
Label transforms are used to handle label overlap, overflow, etc., improving label readability.
| Transform | Type | Purpose |
|---|---|---|
| Overflow Hide | | Hide labels that exceed the area |
| Overlap Hide | | Automatically hide overlapping labels |
| Overlap Dodge Y | | Y direction offset for overlapping labels |
| Contrast Reverse | | Automatically reverse label color to ensure contrast |
| Exceed Adjust | | Adjust label position when exceeding canvas boundary |
| Overflow Stroke | | Add stroke mark for overflow area |
Detailed Documentation: overflowHide | overlapHide | overlapDodgeY | contrastReverse | exceedAdjust | overflowStroke
18. Patterns / 模式
18. Patterns / Patterns
模式是常见场景的最佳实践,包含迁移指南、性能优化、响应式适配等。
Patterns are best practices for common scenarios, including migration guides, performance optimization, responsive adaptation, etc.
18.1 迁移指南 / Migration (v4 → v5)
18.1 Migration Guide / Migration (v4 → v5)
| v4 (Deprecated) | v5 (Correct) |
|---|---|
| |
| |
| |
| |
| |
| |
详细文档: v4 → v5 迁移
| v4 (Deprecated) | v5 (Correct) |
|---|---|
| |
| |
| |
| |
| |
| |
Detailed Documentation: v4 → v5 Migration
18.2 性能优化 / Performance
18.2 Performance Optimization / Performance
数据预聚合、LTTB 降采样、Canvas 渲染器确认、高频实时数据节流更新。
| 场景 | 数据量 | 建议方案 |
|---|---|---|
| 折线图 | < 1,000 点 | 直接渲染 |
| 折线图 | 1,000 ~ 10,000 点 | 降采样到 500 点以内 |
| 折线图 | > 10,000 点 | 后端聚合 + 时间范围过滤 |
| 散点图 | < 5,000 点 | 直接渲染 |
| 散点图 | 5,000 ~ 50,000 点 | Canvas 渲染 + 降采样 |
详细文档: 性能优化
Data pre-aggregation, LTTB downsampling, Canvas renderer confirmation, throttling updates for high-frequency real-time data.
| Scenario | Data Volume | Recommended Solution |
|---|---|---|
| Line Chart | < 1,000 points | Direct rendering |
| Line Chart | 1,000 ~ 10,000 points | Downsample to less than 500 points |
| Line Chart | > 10,000 points | Backend aggregation + time range filtering |
| Scatter Plot | < 5,000 points | Direct rendering |
| Scatter Plot | 5,000 ~ 50,000 points | Canvas rendering + downsampling |
Detailed Documentation: Performance Optimization
18.3 响应式适配 / Responsive
18.3 Responsive Adaptation / Responsive
autoFit 自适应、ResizeObserver 动态调整、移动端字体/边距适配。
详细文档: 响应式适配
autoFit adaptation, ResizeObserver dynamic adjustment, mobile font/margin adaptation.
Detailed Documentation: Responsive Adaptation