Overview
G2 v5 is AntV's grammar-of-graphics charting library. It uses Spec Mode — a declarative, JSON-like configuration style. Generated examples should start from a complete spec; runtime code may later merge a local update through chart.options().
import { Chart } from '@antv/g2';
const chart = new Chart({ container: 'container', autoFit: true });
chart.options({
type: 'interval',
data: [{ genre: 'Sports', sold: 275 }],
encode: { x: 'genre', y: 'sold' },
});
chart.render();
CDN Usage
<script src="https://unpkg.com/@antv/g2@5/dist/g2.min.js"></script>
<script>
const chart = new G2.Chart({ container: 'container', autoFit: true });
chart.options({
type: 'interval',
data: [{ genre: 'Sports', sold: 275 }],
encode: { x: 'genre', y: 'sold' },
});
chart.render();
</script>
Content Retrieval Service
When using AntV G2 for data visualization, if you need to understand the concepts, usage, API, examples, and other aspects of G2 v5, you can use the provided context retrieval service. When using the skill, content is retrieved via an antv HTTP API server using GET requests.
- Host:
https://sive.antv.antgroup.com - Endpoint:
/api/v1/context/retrieve - Method:
GET - Parameters:
query,library,topK,content,maxTokens
Retrieve reference documents by query (hybrid search = FTS + vector + RRF fusion).
| Parameter | Type | Required | Description |
|---|---|---|---|
query |
string | ✅ | Search keywords, e.g. bar chart interval |
library |
string | ✅ | Library name: g2, g6, x6 |
topK |
number | Number of results to return (default: 5) | |
content |
boolean | Return full reference doc markdown (default: true) | |
maxTokens |
number | Max tokens per result (default: unlimited) |
curl "https://sive.antv.antgroup.com/api/v1/context/retrieve?query=bar+chart+stacked&library=g2"
Critical Rules
MUST: Use V5 Spec Mode ONLY
// ❌ WRONG — V4 chain API (deprecated, will not render)
chart.interval()
.data([...])
.encode('x', 'genre')
.encode('y', 'sold')
.style({ radius: 4 });
// ✅ CORRECT — V5 Spec Mode
chart.options({
type: 'interval',
data: [...],
encode: { x: 'genre', y: 'sold' },
style: { radius: 4 },
});
Multi-mark overlays use view + children
chart.options() supports incremental deep-merge updates, which is useful for runtime interaction. For generated one-shot code, provide a complete initial spec. To create independent overlay marks, use one type: 'view' with children; sequentially changing the root type does not create an overlay.
// ❌ WRONG — this changes one root mark from line to point; it does not overlay them
chart.options({ type: 'line', data, encode: { x: 'date', y: 'value' } });
chart.options({ type: 'point', data, encode: { x: 'date', y: 'value' } });
// ✅ CORRECT — children array for multi-mark
chart.options({
type: 'view',
data,
children: [
{ type: 'line', encode: { x: 'date', y: 'value' } },
{ type: 'point', encode: { x: 'date', y: 'value' } },
],
});
MUST: container is mandatory, chart.render() at the end
// ❌ WRONG — no container, no render
const chart = new Chart();
chart.options({ type: 'interval', data });
// ✅ CORRECT
const chart = new Chart({ container: 'container', autoFit: true });
chart.options({ type: 'interval', data, encode: { x: 'genre', y: 'sold' } });
chart.render();
MUST: Correct mark types only
| ❌ Hallucinated (from ECharts/Vega) | ✅ G2 correct replacement |
|---|---|
type: 'ruleX' |
type: 'lineX' |
type: 'ruleY' |
type: 'lineY' |
type: 'regionX' |
type: 'rangeX' |
type: 'regionY' |
type: 'rangeY' |
type: 'venn' |
type: 'path' + transform |
Legal G2 marks: interval, line, area, point, rect, cell, text, image, path, polygon, shape, link, connector, vector, lineX, lineY, rangeX, rangeY, range, box, boxplot, density, heatmap, beeswarm, treemap, pack, partition, tree, sankey, chord, wordCloud, gauge, liquid. sunburst requires @antv/g2-extension-plot.
MUST: encode is an object, transform is an array
// ❌ WRONG
.encode('x', 'genre')
.transform: { type: 'stackY' }
// ✅ CORRECT
encode: { x: 'genre', y: 'sold' }
transform: [{ type: 'stackY' }]
MUST: labels is plural; range encodings use mark-appropriate channels
// ❌ WRONG
label: { text: 'sold' }
// ✅ CORRECT
labels: [{ text: 'sold' }]
// Interval / link ranges may use either a two-field array or y + y1.
encode: { y: ['start', 'end'] }
// RangeY explicitly uses y + y1.
encode: { y: 'start', y1: 'end' }
MUST: No d3 in user code
// ❌ WRONG — d3 is not exposed in user scope
const total = d3.sum(data, d => d.value);
// ✅ CORRECT — use native JS or G2 built-in transforms
const total = data.reduce((sum, d) => sum + d.value, 0);
MUST: No white/near-white fill, no padding as array
// ❌ WRONG
style: { fill: '#fff' } // invisible on white background
padding: [40, 30, 40, 50] // invalid in G2 v5
// ✅ CORRECT
encode: { color: 'group' } // let G2 assign colors
padding: 40 // single number or 'auto'
MUST: Transpose is a transform, not a coordinate type
// ❌ WRONG
coordinate: { type: 'transpose' }
// ✅ CORRECT
coordinate: { transform: [{ type: 'transpose' }] }
Default Aesthetics / Default visual baseline
The goal is to be clear, restrained, and readable by default, rather than adding the same decoration to every chart. Follow the decisions below first, then retrieve as needed default+aesthetics+design for complete examples.
Note the distinction between two kinds of “default.” The G2 engine default (
theme/create.ts) isline.lineWidth: 1、area.fillOpacity: 0.85, rectangularradiuswith no rounded corners; theradius: 4/lineWidth: 2/fillOpacity: 0.5~0.6in this section's Mark baseline is this skill'sagreed value, used to override the engine default to make generated examples look better, and must be written explicitly instyle; it does not take effect by omission.
- General:
container, complete initialchart.options()spec、chart.render()are required; for ordinary embedded charts, preferautoFit: true、theme: 'classic'andpadding: 'auto'。classicas light presets explicitly chosen for stable visuals, not the engine default theme (the engine default is inferred to belight); dark containers useclassicDark. Both share the samecategory10palette (preferred#5B8FF9), so the stable primary color is usable under both light and dark themes. - Color expresses semantics: use
encode.colorand legends only when color represents an independent series, state, or grouping. Single-metric categorical comparisons use a stable single color (such asstyle.fill: '#5B8FF9', which is legal as a style value) and turn off the color legend, avoiding rainbow bars and redundant legends. What is prohibited is storing hex strings in the data and then encoding them as a categorical field inencode.color. - Mark baseline(agreed values, overriding engine defaults): interval uses
radius: 4(engine default has no rounded corners); line useslineWidth: 2(engine default1); area usesfillOpacity: 0.5~0.6(engine default0.85, which is rather solid; lowering it makes it more breathable). These values must all be written explicitly instyle; they do not take effect by omission; no gradients, shadows, or custom animations are needed. - Text uses only known semantics: when fields/units/sources are clear, add semantic axis titles, tooltip names, and formatters; when there is a report context or the user provides a title, add a top-level
title. When information is unknown, omit it; do not fabricate units, sources, or subtitles. - Labels chosen by density: data that is sparse and needs precise reading may have labels added; for dense scatter plots, multi-series line charts, or many categories, rely on tooltips by default. inside labels use
contrastReverse, and when collisions occur useoverlapHide/overlapDodgeY/overflowHide;dx/dyonly for subtle adjustments after avoidance. - Special charts: for pie/donut charts with a few categories, prefer external labels; when there are more categories, switch to legend; do not repeat both by default. Bubble charts keep G2's default sqrt size mapping, set
size.rangeaccording to the data range, and hide the size legend only when it does not help understanding.
Gradients, shadows, sliders, scrollbars, custom animations, and 3D bubbles are all enhancements for when the user explicitly requests “report-grade / refined”; before adding them, you must confirm they will not obscure the data or reduce label contrast.
Quick Reference
| User Intent | Retrieve Query |
|---|---|
| Chart initialization, container, autoFit | GET /api/v1/context/retrieve?query=chart+init&library=g2 |
| Bar / column chart | GET /api/v1/context/retrieve?query=bar+chart+interval&library=g2 |
| Line / area chart | GET /api/v1/context/retrieve?query=line+area+chart&library=g2 |
| Pie / donut / rose chart | GET /api/v1/context/retrieve?query=pie+chart+theta&library=g2 |
| Scatter / bubble | GET /api/v1/context/retrieve?query=scatter+point+bubble&library=g2 |
| Treemap / sunburst / pack | GET /api/v1/context/retrieve?query=treemap+sunburst+pack&library=g2 |
| Heatmap / density / boxplot | GET /api/v1/context/retrieve?query=heatmap+density+boxplot&library=g2 |
| Funnel / gauge / wordcloud | GET /api/v1/context/retrieve?query=funnel+gauge+wordcloud&library=g2 |
| Encode channels (x, y, color, size) | GET /api/v1/context/retrieve?query=encode+channel&library=g2 |
| Scale / palette / color range | GET /api/v1/context/retrieve?query=scale+palette+color&library=g2 |
| Coordinate (polar, theta, transpose) | GET /api/v1/context/retrieve?query=coordinate+polar+theta+transpose&library=g2 |
| Transform (stack, normalize, sort) | GET /api/v1/context/retrieve?query=transform+stack+normalize&library=g2 |
| Axis / legend / tooltip / labels | GET /api/v1/context/retrieve?query=axis+legend+tooltip+label&library=g2 |
| Interaction (brush, highlight, drilldown) | GET /api/v1/context/retrieve?query=interaction+brush+highlight&library=g2 |
| Theme / dark mode | GET /api/v1/context/retrieve?query=theme+dark+classicDark&library=g2 |
| Default Aesthetics / Visual baseline | GET /api/v1/context/retrieve?query=default+aesthetics+design&library=g2 |
| Animation | GET /api/v1/context/retrieve?query=animation+animate&library=g2 |
| Data fetch / filter / sort | GET /api/v1/context/retrieve?query=data+fetch+filter+sort&library=g2 |
| Facet / view composition | GET /api/v1/context/retrieve?query=facet+view+composition&library=g2 |
| Chart type selection guide | GET /api/v1/context/retrieve?query=chart+type+selection&library=g2 |
| Rendering troubleshoot | GET /api/v1/context/retrieve?query=rendering+troubleshoot+debug&library=g2 |
Dependencies
@antv/g2— G2 v5 charting engine