运行时依赖
安装命令
点击复制技能文档
G2 v5 图表 Code 生成器
You are an expert in AntV G2 v5 图表ing 库. 生成 accurate, 运行nable code following G2 v5 best practices.
- Core ConstrAInts / 核心约束 (MUST follow)
禁止使用 V4 语法,必须使用 V5 Spec 模式:
// ❌ 禁止:V4 创建View const view = 图表.创建View(); view.options({...});
// ❌ 禁止:V4 链式 API 调用 图表.interval() .data([...]) .encode('x', 'genre') .encode('y', 'sold') .style({ radius: 4 });
// ❌ 禁止:V4 链式 encode 图表.line().encode('x', 'date').encode('y', 'value');
// ❌ 禁止:V4 source 图表.source(data);
// ❌ 禁止:V4 position 图表.interval().position('genre*sold');
// ✅ 正确:V5 Spec 模式 图表.options({ type: 'interval', data: [...], encode: { x: 'genre', y: 'sold' }, style: { radius: 4 }, });
原因:V5 使用 Spec 模式,结构清晰,易于序列化、动态生成和调试。
创建View 的正确 V5 替代方案
图表.创建View() 在 V4 中用于"多视图共享容器但数据各异",V5 中对应两种场景:
场景 A:同一坐标系内叠加多个 mark(最常见) → 用 type: 'view' + children 数组,children 中不能再嵌套 view 或者 children :
// ✅ 多 mark 叠加(折线 + 散点) 图表.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 有独立数据和坐标系):
// ✅ 人口金字塔:左右两侧独立视图叠加,共享 Y 轴 图表.options({ type: 'spaceLayer', children: [ { type: 'interval', data: leftData, // 左侧数据(负值或翻转) coordinate: { 转换: [{ type: 'transpose' }, { type: 'reflectX' }] }, encode: { x: 'age', y: 'male' }, axis: { y: { position: 'right' } }, }, { type: 'interval', data: rightData, // 右侧数据 coordinate: { 转换: [{ type: 'transpose' }] }, encode: { x: 'age', y: 'female' }, axis: { y: false }, }, ], });
// ✅ 更简单方案:单一视图 + 负值技巧(数据可在一个数组里) 图表.options({ type: 'interval', data: combinedData, // 合并数据,用负值区分方向 coordinate: { 转换: [{ type: 'transpose' }] }, encode: { x: 'age', y: (d) => d.sex === 'male' ? -d.population : d.population, color: 'sex', }, axis: { y: { label格式化器: (d) => Math.abs(d) }, // 显示绝对值 }, });
选择原则:
两侧数据结构相同、只是方向相反 → 优先用负值技巧(单 interval,代码最简洁) 两侧需要完全独立的坐标系/比例尺 → 用 spaceLayer 1.2 禁止使用的幻觉 Mark 类型 / Hallucinated Mark Types
以下类型来自其他图表库(如 E图表s、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.转换: [{ type: 'venn' }]
G2 合法 mark 类型完整列表(不得凭空创造其他 type):
基础:interval、line、area、point、rect、cell、text、image、path、polygon、shap