antv-g2-chart

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

G2 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)

  1. container
    is mandatory
    :
    new Chart({ container: 'container', ... })
  2. Use Spec Mode ONLY:
    chart.options({ type: 'interval', data, encode: {...} })
    (V4 链式 API 见 Forbidden Patterns)
  3. chart.options()
    只能调用一次
    :多次调用会完整覆盖前一次配置,只有最后一次生效。多 mark 叠加必须用
    type: 'view'
    +
    children
    数组,而不是多次调用
    chart.options()
  4. encode
    object
    :
    encode: { x, y }
    (禁止 V4 的
    .position('x*y')
  5. transform
    must be array
    :
    transform: [{ type: 'stackY' }]
  6. labels
    is plural
    : Use
    labels: [{ text: 'field' }]
    not
    label: {}
  7. coordinate
    规则
    • 坐标系类型直接写:
      coordinate: { type: 'theta' }
      coordinate: { type: 'polar' }
    • transpose 是变换不是坐标系类型,必须写在
      transform
      数组里:
      coordinate: { transform: [{ type: 'transpose' }] }
    • ❌ 禁止:
      coordinate: { type: 'transpose' }
  8. 范围编码(甘特图、candlestick 等):
    encode: { y: 'start', y1: 'end' }
    ,禁止
    y: ['start', 'end']
  9. 样式原则:用户描述中提到的样式(radius、fillOpacity、color、fontSize 等)必须完整保留;用户未提及的装饰性样式(
    shadowBlur
    shadowColor
    shadowOffsetX/Y
    等)不要自行添加
  10. animate
    规则
    :用户未明确要求动画时不要添加
    animate
    配置(G2 自带默认动画),只有用户明确描述动画需求时才添加
  11. scale.color.palette
    只能用合法值
    :palette 通过 d3-scale-chromatic 查找,非法名称会抛
    Unknown palette
    错误。不要推断或创造不存在的名称(如
    'blueOrange'
    'redGreen'
    'hot'
    'jet'
    'coolwarm'
    等均非法)。合法的常用值:顺序色阶
    'blues'|'greens'|'reds'|'ylOrRd'|'viridis'|'plasma'|'turbo'
    ;发散色阶
    'rdBu'|'rdYlGn'|'spectral'
    ;不确定时用
    range: ['#startColor', '#endColor']
    自定义替代
  12. 禁止在用户代码中使用
    d3.*
    :G2 内部使用 d3,但
    d3
    对象不会暴露到用户代码作用域,调用
    d3.sum()
    等会抛
    ReferenceError: d3 is not defined
    。如需聚合,优先使用 G2 内置选项(如
    sortX
    reducer: 'sum'
    ),不得不自定义时用原生 JS:
    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))
  13. 用户未指定配色时,禁止使用白色或近白色作为图形填充色
    style: { fill: '#fff' }
    style: { fill: 'white' }
    style: { fill: '#ffffff' }
    等在白色背景下会让图形完全不可见。未指定配色时应依赖 G2 的
    encode.color
    自动分配主题色,或使用有明确视觉区分度的颜色(如
    '#5B8FF9'
    )。以下是合法例外:label 文字
    fill: '#fff'
    (深色背景内标签)、分隔线
    stroke: '#fff'
    (堆叠/pack/treemap 的分隔白线)
  14. 用户未指定容器时
    container
    默认为
    'container'
    ,不要通过
    document.createElement('div')
    进行创建,代码末尾必须有
    chart.render();
  1. container
    is mandatory
    :
    new Chart({ container: 'container', ... })
  2. Use Spec Mode ONLY:
    chart.options({ type: 'interval', data, encode: {...} })
    (V4 chained API see Forbidden Patterns)
  3. chart.options()
    can only be called once
    : Multiple calls will completely overwrite the previous configuration, only the last one takes effect. Multiple mark overlays must use
    type: 'view'
    +
    children
    array instead of calling
    chart.options()
    multiple times
  4. encode
    object
    :
    encode: { x, y }
    (Forbidden: V4's
    .position('x*y')
  5. transform
    must be array
    :
    transform: [{ type: 'stackY' }]
  6. labels
    is plural
    : Use
    labels: [{ text: 'field' }]
    not
    label: {}
  7. coordinate
    rules
    • Coordinate type is written directly:
      coordinate: { type: 'theta' }
      ,
      coordinate: { type: 'polar' }
    • transpose is a transform not a coordinate type, must be written in the
      transform
      array:
      coordinate: { transform: [{ type: 'transpose' }] }
    • ❌ Forbidden:
      coordinate: { type: 'transpose' }
  8. Range encoding(Gantt chart, candlestick, etc.):
    encode: { y: 'start', y1: 'end' }
    , forbidden:
    y: ['start', 'end']
  9. 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
    ,
    shadowOffsetX/Y
    , etc.) should not be added arbitrarily
  10. animate
    rules
    : Do not add
    animate
    configuration when users do not explicitly request animation (G2 has built-in default animations), only add the corresponding animate configuration when users clearly describe animation requirements
  11. scale.color.palette
    can only use valid values
    : Palettes are found via d3-scale-chromatic, invalid names will throw
    Unknown palette
    errors. Do not infer or create non-existent names (such as
    'blueOrange'
    ,
    'redGreen'
    ,
    'hot'
    ,
    'jet'
    ,
    'coolwarm'
    are all invalid). Valid common values: sequential color scales
    'blues'|'greens'|'reds'|'ylOrRd'|'viridis'|'plasma'|'turbo'
    ; diverging color scales
    'rdBu'|'rdYlGn'|'spectral'
    ; when unsure, use custom alternative with
    range: ['#startColor', '#endColor']
  12. Forbidden to use
    d3.*
    in user code
    : G2 uses d3 internally, but the
    d3
    object is not exposed to the user code scope, calling
    d3.sum()
    etc. will throw
    ReferenceError: d3 is not defined
    . If aggregation is needed, prioritize using G2 built-in options (such as
    reducer: 'sum'
    in
    sortX
    ), if custom implementation is unavoidable, use native JS:
    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))
  13. When users do not specify color scheme, forbidden to use white or near-white as graphic fill color:
    style: { fill: '#fff' }
    ,
    style: { fill: 'white' }
    ,
    style: { fill: '#ffffff' }
    etc. will make the graphic completely invisible on white background. When no color scheme is specified, rely on G2's
    encode.color
    to automatically assign theme colors, or use colors with clear visual distinction (such as
    '#5B8FF9'
    ). Valid exceptions: label text
    fill: '#fff'
    (labels in dark backgrounds), separator lines
    stroke: '#fff'
    (white separators for stack/pack/treemap)
  14. When users do not specify container:
    container
    defaults to
    'container'
    , do not create via
    document.createElement('div')
    , the code must end with
    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 替代方案

Correct V5 Alternative for
createView

chart.createView()
在 V4 中用于"多视图共享容器但数据各异",V5 中对应两种场景:
场景 A:同一坐标系内叠加多个 mark(最常见) → 用
type: 'view'
+
children
数组,
children
中不能再嵌套
view
或者
children
javascript
// ✅ 多 mark 叠加(折线 + 散点)
chart.options({
  type: 'view',
  data,
  children: [
    { type: 'line',  encode: { x: 'date', y: 'value' } },
    { type: 'point', encode: { x: 'date', y: 'value' } },
  ],
});
场景 B:多个独立坐标系并排/叠加(如人口金字塔、butterfly 图) → 用
type: 'spaceLayer'
+
children
(各子 view 有独立数据和坐标系):
javascript
// ✅ 人口金字塔:左右两侧独立视图叠加,共享 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()
in V4 is used for "multiple views sharing container but with different data", in V5 it corresponds to two scenarios:
Scenario A: Overlay multiple marks in the same coordinate system (most common) → Use
type: 'view'
+
children
array,
children
cannot nest
view
or
children
again:
javascript
// ✅ 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
type: 'spaceLayer'
+
children
(each sub-view has independent data and coordinate system):
javascript
// ✅ 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
    interval
    , most concise code)
  • 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 中不存在,使用将导致运行时报错:
❌ 错误写法✅ 正确替换
type: 'ruleX'
type: 'lineX'
(垂直参考线)
type: 'ruleY'
type: 'lineY'
(水平参考线)
type: 'regionX'
type: 'rangeX'
(X 轴区间高亮)
type: 'regionY'
type: 'rangeY'
(Y 轴区间高亮)
type: 'venn'
type: 'path'
+
data.transform: [{ type: 'venn' }]
G2 合法 mark 类型完整列表(不得凭空创造其他 type):
  • 基础:
    interval
    line
    area
    point
    rect
    cell
    text
    image
    path
    polygon
    shape
  • 连接:
    link
    connector
    vector
  • 参考线/区域:
    lineX
    lineY
    rangeX
    rangeY
    range
    (极少用,仅在 x/y 均需限定二维矩形时使用,且数据的 x/y 字段必须是
    [start,end]
    数组)
  • 统计:
    box
    boxplot
    density
    heatmap
    beeswarm
  • 层次/关系:
    treemap
    pack
    partition
    tree
    sankey
    chord
    forceGraph
  • 特殊:
    wordCloud
    gauge
    liquid
  • 需引入扩展包:
    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
type: 'ruleX'
type: 'lineX'
(vertical reference line)
type: 'ruleY'
type: 'lineY'
(horizontal reference line)
type: 'regionX'
type: 'rangeX'
(X-axis interval highlight)
type: 'regionY'
type: 'rangeY'
(Y-axis interval highlight)
type: 'venn'
type: 'path'
+
data.transform: [{ type: 'venn' }]
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
    ,
    polygon
    ,
    shape
  • Connection:
    link
    ,
    connector
    ,
    vector
  • Reference lines/areas:
    lineX
    ,
    lineY
    ,
    rangeX
    ,
    rangeY
    ;
    range
    (rarely used, only when both x/y need to limit 2D rectangles, and the x/y fields of data must be
    [start,end]
    arrays)
  • Statistical:
    box
    ,
    boxplot
    ,
    density
    ,
    heatmap
    ,
    beeswarm
  • Hierarchy/Relationship:
    treemap
    ,
    pack
    ,
    partition
    ,
    tree
    ,
    sankey
    ,
    chord
    ,
    forceGraph
  • Special:
    wordCloud
    ,
    gauge
    ,
    liquid
  • Need to import extension package:
    sunburst
    (requires
    @antv/g2-extension-plot
    , see Sunburst Chart)

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
X 轴位置
encode: { x: 'month' }
y
Y 轴位置
encode: { y: 'value' }
color
颜色
encode: { color: 'category' }
size
大小
encode: { size: 'population' }
shape
形状
encode: { shape: 'type' }
详细文档: encode 通道系统
Encode maps data fields to visual channels, which is the core concept of G2.
ChannelPurposeExample
x
X-axis position
encode: { x: 'month' }
y
Y-axis position
encode: { y: 'value' }
color
Color
encode: { color: 'category' }
size
Size
encode: { size: 'population' }
shape
Shape
encode: { shape: 'type' }
Detailed Documentation: Encode Channel System

4.3 视图组合 (view + children)

4.3 View Composition (view + children)

使用
view
类型配合
children
数组组合多个 mark。
javascript
chart.options({
  type: 'view',
  data,
  children: [
    { type: 'line', encode: { x: 'date', y: 'value' } },
    { type: 'point', encode: { x: 'date', y: 'value' } },
  ],
});
详细文档: 视图组合

Use
view
type with
children
array to combine multiple marks.
javascript
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
比较柱状图、条形图
interval
趋势折线图、面积图
line
area
占比饼图、环形图
interval
+
theta
分布直方图、箱线图
rect
boxplot
相关散点图、气泡图
point
层级矩形树图、旭日图
treemap
sunburst
(需扩展包)
详细文档: 图表类型选择指南
Select the appropriate chart type based on data characteristics and visualization goals:
Data RelationshipRecommended ChartMark
ComparisonBar chart, column chart
interval
TrendLine chart, area chart
line
,
area
ProportionPie chart, donut chart
interval
+
theta
DistributionHistogram, box plot
rect
,
boxplot
CorrelationScatter plot, bubble chart
point
HierarchyTreemap, sunburst chart
treemap
,
sunburst
(requires extension package)
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 TypeSuitable DataPerception Accuracy
PositionContinuous/discreteHighest
LengthContinuousHigh
Color (hue)DiscreteMedium
Color (brightness)ContinuousMedium
SizeContinuousMedium-low
ShapeDiscreteLow
Detailed Documentation: Visual Channels

5.3 配色理论 / Color Theory

5.3 Color Theory

选择合适的配色方案提升图表可读性:
场景推荐方案示例
分类数据离散色板
category10
category20
连续数据顺序色板
Blues
RdYlBu
正负对比发散色板
RdYlGn
详细文档: 配色理论

Choose the appropriate color scheme to improve chart readability:
ScenarioRecommended SchemeExample
Categorical DataDiscrete color palette
category10
,
category20
Continuous DataSequential color palette
Blues
,
RdYlBu
Positive/Negative ComparisonDiverging color palette
RdYlGn
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

柱状图用于比较分类数据的大小,是最常用的图表类型。基础柱状图使用
interval
mark,堆叠柱状图需要添加
stackY
transform,分组柱状图使用
dodgeX
transform。
类型Mark关键配置
基础柱状图
interval
-
堆叠柱状图
interval
transform: [{ type: 'stackY' }]
分组柱状图
interval
transform: [{ type: 'dodgeX' }]
百分比柱状图
interval
transform: [{ type: 'normalizeY' }]
水平柱状图
interval
coordinate: { transform: [{ type: 'transpose' }] }
详细文档: 基础柱状图 | 堆叠柱状图 | 分组柱状图 | 百分比柱状图
Bar charts are used to compare the size of categorical data, which is the most commonly used chart type. Basic bar charts use
interval
mark, stacked bar charts need to add
stackY
transform, grouped bar charts use
dodgeX
transform.
TypeMarkKey Configuration
Basic Bar Chart
interval
-
Stacked Bar Chart
interval
transform: [{ type: 'stackY' }]
Grouped Bar Chart
interval
transform: [{ type: 'dodgeX' }]
Normalized Bar Chart
interval
transform: [{ type: 'normalizeY' }]
Horizontal Bar Chart
interval
coordinate: { transform: [{ type: 'transpose' }] }
Detailed Documentation: Basic Bar Chart | Stacked Bar Chart | Grouped Bar Chart | Normalized Bar Chart

6.2 折线图系列 / Line

6.2 Line Series / Line

折线图用于展示数据随时间或有序类别的变化趋势。支持单线、多线对比,以及不同插值方式。
类型Mark关键配置
基础折线图
line
-
多系列折线
line
encode: { color: 'category' }
平滑曲线
line
encode: { shape: 'smooth' }
阶梯线
line
encode: { shape: 'step' }
详细文档: 基础折线图 | 多系列折线 | 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.
TypeMarkKey Configuration
Basic Line Chart
line
-
Multi-series Line Chart
line
encode: { color: 'category' }
Smooth Curve
line
encode: { shape: 'smooth' }
Step Line
line
encode: { shape: 'step' }
Detailed Documentation: Basic Line Chart | Multi-series Line Chart | LineX/LineY

6.3 面积图系列 / Area

6.3 Area Series / Area

面积图在折线图基础上填充区域,强调数量随时间的变化程度。堆叠面积图用于展示各部分对整体的贡献。
类型Mark关键配置
基础面积图
area
-
堆叠面积图
area
transform: [{ type: 'stackY' }]
详细文档: 基础面积图 | 堆叠面积图
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.
TypeMarkKey Configuration
Basic Area Chart
area
-
Stacked Area Chart
area
transform: [{ type: 'stackY' }]
Detailed Documentation: Basic Area Chart | Stacked Area Chart

6.4 饼图/环形图 / Arc (Pie/Donut)

6.4 Pie/Donut Chart / Arc (Pie/Donut)

饼图用于展示各部分占整体的比例关系。使用
theta
坐标系配合
interval
mark 实现。
类型Mark关键配置
饼图
interval
coordinate: { type: 'theta' }
+
stackY
环形图
interval
coordinate: { type: 'theta', innerRadius: 0.6 }
详细文档: 饼图 | 环形图
Pie charts are used to show the proportional relationship of each part to the whole. Implemented using
theta
coordinate system with
interval
mark.
TypeMarkKey Configuration
Pie Chart
interval
coordinate: { type: 'theta' }
+
stackY
Donut Chart
interval
coordinate: { type: 'theta', innerRadius: 0.6 }
Detailed Documentation: Pie Chart | Donut Chart

6.5 散点图/气泡图 / Point

6.5 Scatter/Bubble Chart / Point

散点图用于展示两个数值变量的关系,气泡图通过点的大小展示第三个维度。
类型Mark关键配置
散点图
point
encode: { x, y }
气泡图
point
encode: { x, y, size }
详细文档: 散点图 | 气泡图
Scatter plots are used to show the relationship between two numerical variables, bubble charts show a third dimension through the size of points.
TypeMarkKey Configuration
Scatter Plot
point
encode: { x, y }
Bubble Chart
point
encode: { x, y, size }
Detailed Documentation: Scatter Plot | Bubble Chart

6.6 直方图 / Histogram

6.6 Histogram / Histogram

直方图用于展示连续数值数据的分布情况,使用
rect
标记配合
binX
转换实现。与柱状图不同,直方图的柱子之间无间隔,表示数据连续。
类型Mark关键配置
基础直方图
rect
transform: [{ type: 'binX', y: 'count' }]
多分布对比
rect
groupBy
分组
详细文档: 直方图
Histograms are used to show the distribution of continuous numerical data, implemented using
rect
mark with
binX
transform. Different from bar charts, there are no gaps between the bars of histograms, indicating continuous data.
TypeMarkKey Configuration
Basic Histogram
rect
transform: [{ type: 'binX', y: 'count' }]
Multi-distribution Comparison
rect
groupBy
grouping
Detailed Documentation: Histogram

6.7 玫瑰图/玉珏图 / Polar Charts

6.7 Rose/Radial Bar Chart / Polar Charts

极坐标系下的图表,通过半径或弧长表示数值大小,视觉上更加美观。
类型Mark关键配置
玫瑰图
interval
coordinate: { type: 'polar' }
玉珏图
interval
coordinate: { type: 'radial' }
详细文档: 玫瑰图 | 玉珏图
Charts in polar coordinate system, representing numerical size through radius or arc length, which are more visually appealing.
TypeMarkKey Configuration
Rose Chart
interval
coordinate: { type: 'polar' }
Radial Bar Chart
interval
coordinate: { type: 'radial' }
Detailed Documentation: Rose Chart | Radial Bar Chart

6.8 统计分布图 / Distribution

6.8 Statistical Distribution Charts / Distribution

展示数据分布特征的图表,适用于统计分析和探索性数据分析。
类型Mark用途
箱线图
boxplot
数据分布统计
箱型图(Box)
box
手动指定五数概括的箱线图
密度图
density
核密度估计曲线
小提琴图
density
+
boxplot
密度分布 + 统计信息
多边形
polygon
自定义多边形区域
详细文档: 箱线图 | 箱型图(Box) | 密度图 | 小提琴图 | 多边形
Charts showing data distribution characteristics, suitable for statistical analysis and exploratory data analysis.
TypeMarkPurpose
Box Plot
boxplot
Data distribution statistics
Custom Box Plot
box
Box plot with manually specified five-number summary
Density Plot
density
Kernel density estimation curve
Violin Plot
density
+
boxplot
Density distribution + statistical information
Polygon
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用途
桑基图
sankey
流向/转移关系
和弦图
chord
矩阵流向关系
韦恩图
path
+ venn数据变换
集合交集关系(venn 是 data transform,不是 mark type)
弧长连接图
line
+
point
节点链接关系
详细文档: 桑基图 | 和弦图 | 韦恩图 | 弧长连接图
Charts showing relationships between data, suitable for network analysis and set relationship display.
TypeMarkPurpose
Sankey Diagram
sankey
Flow/transfer relationship
Chord Diagram
chord
Matrix flow relationship
Venn Diagram
path
+ venn data transform
Set intersection relationship (venn is data transform, not mark type)
Arc Diagram
line
+
point
Node link relationship
Detailed Documentation: Sankey Diagram | Chord Diagram | Venn Diagram | Arc Diagram

6.10 项目管理图 / Project

6.10 Project Management Charts / Project

适用于项目管理和进度跟踪的图表。
类型Mark用途
甘特图
interval
任务时间安排
子弹图
interval
+
point
KPI 指标展示
详细文档: 甘特图 | 子弹图
Charts suitable for project management and progress tracking.
TypeMarkPurpose
Gantt Chart
interval
Task schedule
Bullet Chart
interval
+
point
KPI indicator display
Detailed Documentation: Gantt Chart | Bullet Chart

6.11 金融图表 / Finance

6.11 Financial Charts / Finance

适用于金融数据分析的专业图表。
类型Mark用途
K线图
link
+
interval
股票四价数据
详细文档: K线图
Professional charts suitable for financial data analysis.
TypeMarkPurpose
K-line Chart
link
+
interval
Stock four-price data
Detailed Documentation: K-line Chart

6.12 多维数据图 / Multivariate

6.12 Multivariate Data Charts / Multivariate

展示多维数据关系的图表。
类型Mark用途
平行坐标系
line
多维数据关系分析
雷达图
line
多维数据对比
详细文档: 平行坐标系 | 雷达图
Charts showing relationships between multivariate data.
TypeMarkPurpose
Parallel Coordinates
line
Multivariate data relationship analysis
Radar Chart
line
Multivariate data comparison
Detailed Documentation: Parallel Coordinates | Radar Chart

6.13 对比图 / Comparison

6.13 Comparison Charts / Comparison

适用于数据对比的图表。
类型Mark用途
双向柱状图
interval
正负数据对比
详细文档: 双向柱状图
Charts suitable for data comparison.
TypeMarkPurpose
Bi-directional Bar Chart
interval
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
向量/箭头标记,风场图等
详细文档: 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.
TypeMarkPurpose
Rectangle
rect
Rectangular area, foundation of histogram/heatmap
Text
text
Text annotation and labels
Image
image
Image mark, data points represented by images
Path
path
Custom path drawing
Link
link
Line between two points
Connector
connector
Connection line between data points
Shape
shape
Custom shape drawing
Vector
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 方向)
rangeX
X 轴区间,
encode: { x: 'start', x1: 'end' }
数值范围高亮(Y 方向)
rangeY
Y 轴区间,
encode: { y: 'min', y1: 'max' }
二维矩形区域
range
x/y 字段为
[start,end]
数组,
encode: { x:'x', y:'y' }
,极少使用
详细文档: range/rangeY | rangeX
Range marks are used to show the interval range of data.
TypeMarkPurpose
Time period/interval highlight (X direction)
rangeX
X-axis interval,
encode: { x: 'start', x1: 'end' }
Value range highlight (Y direction)
rangeY
Y-axis interval,
encode: { y: 'min', y1: 'max' }
2D rectangular area
range
x/y fields are
[start,end]
arrays,
encode: { x:'x', y:'y' }
, rarely used
Detailed Documentation: range/rangeY | rangeX

6.16 分布与打包图 / Distribution & Pack

6.16 Distribution & Pack Charts / Distribution & Pack

类型Mark用途
蜂群图
point
+
pack
数据点紧密排列展示分布
打包图
pack
层级数据的圆形打包
详细文档: 蜂群图 | 打包图
TypeMarkPurpose
Beeswarm Plot
point
+
pack
Data points are closely arranged to show distribution
Pack Chart
pack
Circular packing of hierarchical data
Detailed Documentation: Beeswarm Plot | Pack Chart

6.17 层次结构图 / Hierarchy

6.17 Hierarchy Charts / Hierarchy

展示层级数据的图表,通过面积或半径表示数值占比。
类型Mark用途
矩形树图
treemap
层级数据占比
旭日图
sunburst
⚠️
多层级同心圆展示(需引入 @antv/g2-extension-plot)
分区图
partition
层级数据分区展示
树图
tree
树形层级结构
详细文档: 矩形树图 | 旭日图 | 分区图 | 树图
Charts showing hierarchical data, representing the proportion of values through area or radius.
TypeMarkPurpose
Treemap
treemap
Hierarchical data proportion
Sunburst Chart
sunburst
⚠️
Multi-level concentric circle display (requires @antv/g2-extension-plot)
Partition Chart
partition
Hierarchical data partition display
Tree Diagram
tree
Tree hierarchical structure
Detailed Documentation: Treemap | Sunburst Chart | Partition Chart | Tree Diagram

6.18 其他图表 / Others

6.18 Other Charts / Others

类型Mark用途
热力图
cell
二维矩阵数据可视化
密度热力图
heatmap
连续密度热力图
仪表盘
gauge
指标进度展示
词云
wordCloud
文本频率可视化
水波图
liquid
百分比进度
详细文档: 热力图 | 密度热力图 | 仪表盘 | 词云 | 水波图

TypeMarkPurpose
Heatmap
cell
2D matrix data visualization
Density Heatmap
heatmap
Continuous density heatmap
Gauge
gauge
Indicator progress display
Word Cloud
wordCloud
Text frequency visualization
Liquid Fill Chart
liquid
Percentage progress
Detailed Documentation: Heatmap | Density Heatmap | Gauge | Word Cloud | Liquid Fill Chart

7. Data / 数据变换

7. Data Transforms / Data Transforms

数据变换在数据加载阶段执行,配置在
data.transform
中,影响所有使用该数据的标记。
Data transforms are executed during data loading phase, configured in
data.transform
, affecting all marks using this data.

7.1 Data Transform 类型(配置在
data.transform

7.1 Data Transform Types (configured in
data.transform
)

变换类型用途示例场景
fold
fold
宽表转长表多列数据转多系列
filter
filter
条件过滤数据过滤无效数据
sort
sort
使用回调函数排序自定义排序逻辑
sortBy
sortBy
按字段排序按字段值排序
map
map
数据映射转换添加计算字段
join
join
合并数据表关联外部数据
pick
pick
选择指定字段精简字段
rename
rename
重命名字段字段重命名
slice
slice
截取数据范围分页/截取
ema
ema
指数移动平均时间序列平滑
kde
kde
核密度估计密度图/小提琴图
log
log
打印数据到控制台调试
custom
custom
自定义数据处理复杂转换
TransformTypePurposeExample Scenario
fold
fold
Wide to long tableConvert multi-column data to multi-series
filter
filter
Conditional data filteringFilter invalid data
sort
sort
Sort using callback functionCustom sorting logic
sortBy
sortBy
Sort by fieldSort by field value
map
map
Data mapping transformationAdd calculated fields
join
join
Merge data tablesAssociate external data
pick
pick
Select specified fieldsSimplify fields
rename
rename
Rename fieldsField renaming
slice
slice
Intercept data rangePagination/interception
ema
ema
Exponential moving averageTime series smoothing
kde
kde
Kernel density estimationDensity plot/violin plot
log
log
Print data to consoleDebugging
custom
custom
Custom data processingComplex transformation

7.2 数据格式与模式

7.2 Data Format and Patterns

类型用途
表格数据格式G2 接受的标准表格数据格式说明
数据变换模式Data Transform 和 Mark Transform 的组合使用模式
详细文档: filter | sort | sortBy | fold | slice | ema | kde | log | fetch | 表格数据格式 | 数据变换模式
TypePurpose
Tabular Data FormatDescription of standard tabular data format accepted by G2
Data Transform PatternsCombined 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
数组中,用于数据聚合、防重叠等。
配置位置
transform
数组,与
data
encode
同级,不是
data.transform
中。
javascript
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
transform
array of the mark, used for data aggregation, anti-overlap, etc.
Configuration Position:
transform
array, at the same level as
data
and
encode
, not in
data.transform
.
javascript
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

变换类型用途
堆叠
stackY
数据堆叠,用于堆叠图
分组
dodgeX
数据分组,用于分组图
抖动
jitter
散点抖动避免重叠
X轴抖动
jitterX
X 方向抖动
Y轴抖动
jitterY
Y 方向抖动
打包
pack
紧密排列数据点
详细文档: stackY | dodgeX | jitter | jitterX | jitterY | pack
TransformTypePurpose
Stack
stackY
Data stacking, used for stacked charts
Dodge
dodgeX
Data grouping, used for grouped charts
Jitter
jitter
Scatter jitter to avoid overlap
Jitter X
jitterX
X direction jitter
Jitter Y
jitterY
Y direction jitter
Pack
pack
Closely arrange data points
Detailed Documentation: stackY | dodgeX | jitter | jitterX | jitterY | pack

8.2 聚合变换 / Aggregation

8.2 Aggregation Transforms / Aggregation

变换类型用途
通用分组
group
通用分组聚合
分组聚合
groupX
/
groupY
按维度分组并聚合
分组颜色
groupColor
按颜色分组聚合
分箱
bin
二维分箱
X轴分箱
binX
X 轴方向分箱
采样
sample
数据采样
详细文档: group | groupX | groupY | groupColor | bin | binX | sample
TransformTypePurpose
General Group
group
General grouping aggregation
Group by X
groupX
/
groupY
Group by dimension and aggregate
Group by Color
groupColor
Group by color and aggregate
Bin
bin
2D binning
Bin X
binX
X direction binning
Sample
sample
Data sampling
Detailed Documentation: group | groupX | groupY | groupColor | bin | binX | sample

8.3 排序变换 / Sorting

8.3 Sorting Transforms / Sorting

变换类型用途
X轴排序
sortX
按 X 通道排序
Y轴排序
sortY
按 Y 通道排序
颜色排序
sortColor
按颜色通道排序
详细文档: sortX | sortY | sortColor
TransformTypePurpose
Sort X
sortX
Sort by X channel
Sort Y
sortY
Sort by Y channel
Sort Color
sortColor
Sort by color channel
Detailed Documentation: sortX | sortY | sortColor

8.4 选取变换 / Selection

8.4 Selection Transforms / Selection

变换类型用途
选取
select
全局选取数据
X轴选取
selectX
按 X 分组选取
Y轴选取
selectY
按 Y 分组选取
详细文档: select | selectX | selectY
TransformTypePurpose
Select
select
Global data selection
Select X
selectX
Select by X grouping
Select Y
selectY
Select by Y grouping
Detailed Documentation: select | selectX | selectY

8.5 其他变换 / Others

8.5 Other Transforms / Others

变换类型用途
归一化
normalizeY
Y 轴归一化
差值
diffY
计算差值
对称
symmetryY
Y 轴对称
弹性X
flexX
X 轴弹性布局
堆叠入场
stackEnter
入场动画堆叠
详细文档: normalizeY | diffY | symmetryY | flexX | stackEnter

TransformTypePurpose
Normalize
normalizeY
Y-axis normalization
Diff
diffY
Calculate difference
Symmetry
symmetryY
Y-axis symmetry
Flex X
flexX
X-axis flexible layout
Stack Enter
stackEnter
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

交互类型用途
元素选择
elementSelect
点击选择数据元素
按条件选择
elementSelectBy
按条件批量选择元素
框选
brush
/
brushX
/
brushY
矩形区域选择
二维框选
brushXY
XY 同时框选
轴框选
brushAxis
坐标轴范围选择
图例过滤
legendFilter
点击图例筛选数据
详细文档: elementSelect | elementSelectBy | brush | brushXY | brushAxis | legendFilter
InteractionTypePurpose
Element Select
elementSelect
Click to select data elements
Element Select By
elementSelectBy
Batch select elements by condition
Brush / Brush X / Brush Y
brush
/
brushX
/
brushY
Rectangular area selection
Brush XY
brushXY
XY simultaneous selection
Brush Axis
brushAxis
Coordinate axis range selection
Legend Filter
legendFilter
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
框选区域高亮
详细文档: elementHighlight | elementHighlightBy | elementHoverScale | legendHighlight | brushXHighlight | brushYHighlight | 单轴框选高亮
InteractionTypePurpose
Element Highlight
elementHighlight
Hover to highlight elements
Element Highlight By
elementHighlightBy
Batch highlight elements by condition
Element Hover Scale
elementHoverScale
Element scales up on hover
Legend Highlight
legendHighlight
Hover legend to highlight corresponding elements
Brush X Highlight / Brush Y Highlight
brushXHighlight
/
brushYHighlight
Highlight brush area
Detailed Documentation: elementHighlight | elementHighlightBy | elementHoverScale | legendHighlight | brushXHighlight | brushYHighlight | Single Axis Brush Highlight

9.3 过滤类交互 / Filter

9.3 Filter Interactions / Filter

交互类型用途
滑动条过滤
sliderFilter
滑动条筛选数据范围
滚动条过滤
scrollbarFilter
滚动条筛选数据
框选过滤
brushFilter
框选区域过滤数据
X轴框选过滤
brushXFilter
X 轴方向框选过滤
Y轴框选过滤
brushYFilter
Y 轴方向框选过滤
自适应过滤
adaptiveFilter
自适应数据过滤
详细文档: sliderFilter | scrollbarFilter | brushFilter | brushXFilter | brushYFilter | adaptiveFilter
InteractionTypePurpose
Slider Filter
sliderFilter
Slider to filter data range
Scrollbar Filter
scrollbarFilter
Scrollbar to filter data
Brush Filter
brushFilter
Brush area to filter data
Brush X Filter
brushXFilter
X direction brush to filter data
Brush Y Filter
brushYFilter
Y direction brush to filter data
Adaptive Filter
adaptiveFilter
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
多图表联动索引线
详细文档: tooltip | poptip | drilldown | treemapDrilldown | fisheye | sliderWheel | elementPointMove | chartIndex

InteractionTypePurpose
Tooltip
tooltip
Hover to show data details
Poptip
poptip
Concise poptip
Drilldown
drilldown
Hierarchical data drilldown
Treemap Drilldown
treemapDrilldown
Treemap hierarchical drilldown
Fisheye
fisheye
Fisheye magnifier effect
Slider Wheel
sliderWheel
Mouse wheel controls slider
Element Point Move
elementPointMove
Drag data points to move
Chart Index
chartIndex
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).
TypePurpose
Category LegendColor mapping description of discrete categorical data
Continuous LegendColor/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

组件用途
标题图表标题
标签数据标签
滚动条数据滚动浏览
滑动条数据范围选择
标注数据标注和辅助线
详细文档: 标题 | 标签 | 滚动条 | 滑动条 | 标注

ComponentPurpose
TitleChart title
LabelData label
ScrollbarData scroll browsing
SliderData range selection
AnnotationData 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示例
数值字段
linear
{ value: 100 }
→ linear
分类字段
band
{ category: 'A' }
→ band
Date 对象
time
{ date: new Date() }
→ time
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说明
对数刻度
log
跨数量级数据
幂函数刻度
pow
非线性数据映射
平方根刻度
sqrt
非负数据的压缩
字符串日期
time
日期字段是字符串而非 Date 对象时
自定义映射
ordinal
离散值到离散值
渐变色
sequential
连续数值到颜色渐变
分段映射
threshold
按阈值分段映射到颜色
等量分段
quantize
/
quantile
连续数据离散化
G2 automatically infers scale type based on data type, do not manually specify type unless necessary:
Data TypeAutomatically Inferred ScaleExample
Numeric Field
linear
{ value: 100 }
→ linear
Categorical Field
band
{ category: 'A' }
→ band
Date Object
time
{ date: new Date() }
→ time
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:
ScenariotypeDescription
Logarithmic Scale
log
Cross-order-of-magnitude data
Power Scale
pow
Non-linear data mapping
Square Root Scale
sqrt
Compression of non-negative data
String Date
time
When date field is string instead of Date object
Custom Mapping
ordinal
Discrete to discrete mapping
Gradient Color
sequential
Continuous value to color gradient
Threshold Mapping
threshold
Segment mapping to color by threshold
Equal Quantization
quantize
/
quantile
Discretization of continuous data

11.2 比例尺类型

11.2 Scale Types

比例尺类型用途
线性
linear
连续数值映射(默认)
分类
band
离散分类映射(默认)
point
离散点位置映射
时间
time
时间数据映射
对数
log
对数刻度
幂/平方根
pow
/
sqrt
幂函数/平方根映射
序数
ordinal
离散值到离散值映射
顺序
sequential
连续值到颜色渐变
分位数/量化
quantile
/
quantize
连续数据离散化映射
阈值
threshold
按阈值分段映射
详细文档: linear | band | point | time | log | pow/sqrt | ordinal | sequential | quantile/quantize | threshold

ScaleTypePurpose
Linear
linear
Continuous numeric mapping (default)
Band
band
Discrete categorical mapping (default)
Point
point
Discrete point position mapping
Time
time
Time data mapping
Log
log
Logarithmic scale
Power / Square Root
pow
/
sqrt
Power function/square root mapping
Ordinal
ordinal
Discrete to discrete mapping
Sequential
sequential
Continuous value to color gradient
Quantile / Quantize
quantile
/
quantize
Discretization mapping of continuous data
Threshold
threshold
Segment mapping by threshold
Detailed Documentation: linear | band | point | time | log | pow/sqrt | ordinal | sequential | quantile/quantize | threshold

12. Coordinates / 坐标系

12. Coordinates / Coordinates

坐标系定义数据到画布位置的映射方式,不同坐标系产生不同图表形态。
坐标系类型用途
笛卡尔
cartesian
直角坐标系(默认)
极坐标
polar
雷达图、玫瑰图
Theta
theta
饼图、环形图
径向
radial
径向坐标系,玉珏图
转置
transpose
X/Y 轴交换
平行
parallel
平行坐标系
螺旋
helix
螺旋坐标系
鱼眼
fisheye
局部放大效果
详细文档: 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 SystemTypePurpose
Cartesian
cartesian
Rectangular coordinate system (default)
Polar
polar
Radar chart, rose chart
Theta
theta
Pie chart, donut chart
Radial
radial
Radial coordinate system, radial bar chart
Transpose
transpose
X/Y axis swap
Parallel
parallel
Parallel coordinate system
Helix
helix
Helix coordinate system
Fisheye
fisheye
Local magnification effect
Detailed Documentation: cartesian | polar | theta | radial | transpose | parallel | helix | fisheye

13. Compositions / 组合视图

13. View Compositions / View Compositions

组合视图用于创建多图表布局,如分面、多视图叠加等。
组合类型用途
基础视图
view
单视图容器,组合多个 mark
分面图
facetRect
按维度拆分矩形网格多图
圆形分面
facetCircle
按维度拆分环形多图
重复矩阵
repeatMatrix
多变量组合矩阵图
空间层叠
spaceLayer
多图层叠加
空间弹性
spaceFlex
弹性布局
时间关键帧
timingKeyframe
动画序列
地理视图
geoView
地理坐标系视图
地图
geoPath
地理路径绘制
详细文档: view | facetRect | facetCircle | repeatMatrix | spaceLayer | spaceFlex | timingKeyframe | geoView | 地图

View compositions are used to create multi-chart layouts, such as facets, multi-view overlays, etc.
CompositionTypePurpose
Basic View
view
Single view container, combining multiple marks
Facet Rect
facetRect
Split into rectangular grid multi-charts by dimension
Facet Circle
facetCircle
Split into circular multi-charts by dimension
Repeat Matrix
repeatMatrix
Multi-variable combination matrix chart
Space Layer
spaceLayer
Multi-layer overlay
Space Flex
spaceFlex
Flexible layout
Timing Keyframe
timingKeyframe
Animation sequence
Geo View
geoView
Geographic coordinate system view
Map
geoPath
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
animate
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.
Detailed Documentation: Animation Introduction | Animation Types | Keyframe Animation

17. Label Transforms / 标签变换

17. Label Transforms / Label Transforms

标签变换用于处理标签重叠、溢出等问题,提升标签可读性。
变换类型用途
溢出隐藏
overflowHide
超出区域的标签隐藏
重叠隐藏
overlapHide
重叠标签自动隐藏
重叠偏移
overlapDodgeY
重叠标签 Y 方向偏移
对比反转
contrastReverse
标签颜色自动反转以保证对比度
溢出调整
exceedAdjust
超出画布边界的标签位置调整
溢出描边
overflowStroke
溢出区域添加描边标记
详细文档: overflowHide | overlapHide | overlapDodgeY | contrastReverse | exceedAdjust | overflowStroke

Label transforms are used to handle label overlap, overflow, etc., improving label readability.
TransformTypePurpose
Overflow Hide
overflowHide
Hide labels that exceed the area
Overlap Hide
overlapHide
Automatically hide overlapping labels
Overlap Dodge Y
overlapDodgeY
Y direction offset for overlapping labels
Contrast Reverse
contrastReverse
Automatically reverse label color to ensure contrast
Exceed Adjust
exceedAdjust
Adjust label position when exceeding canvas boundary
Overflow Stroke
overflowStroke
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)
chart.source(data)
chart.options({ data })
.position('x*y')
encode: { x: 'x', y: 'y' }
.color('field')
encode: { color: 'field' }
.adjust('stack')
transform: [{ type: 'stackY' }]
.adjust('dodge')
transform: [{ type: 'dodgeX' }]
label: {}
labels: [{}]
详细文档: v4 → v5 迁移
v4 (Deprecated)v5 (Correct)
chart.source(data)
chart.options({ data })
.position('x*y')
encode: { x: 'x', y: 'y' }
.color('field')
encode: { color: 'field' }
.adjust('stack')
transform: [{ type: 'stackY' }]
.adjust('dodge')
transform: [{ type: 'dodgeX' }]
label: {}
labels: [{}]
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.
ScenarioData VolumeRecommended Solution
Line Chart< 1,000 pointsDirect rendering
Line Chart1,000 ~ 10,000 pointsDownsample to less than 500 points
Line Chart> 10,000 pointsBackend aggregation + time range filtering
Scatter Plot< 5,000 pointsDirect rendering
Scatter Plot5,000 ~ 50,000 pointsCanvas 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