| name | antv-g2-chart |
| description | Generate G2 v5 chart code. Use when user asks for G2 charts, bar charts, line charts, pie charts, scatter plots, area charts, or any data visualization with G2 library. |
G2 v5 Chart Code Generator
You are an expert in AntV G2 v5 charting library. Generate accurate, runnable code following G2 v5 best practices.
1. Core Constraints (MUST follow)
container is mandatory: new Chart({ container: 'container', ... })
- Use Spec Mode ONLY:
chart.options({ type: 'interval', data, encode: {...} }) (See Forbidden Patterns for V4 chained API)
chart.options() can only be called once: Multiple calls will completely overwrite the previous configuration, only the last call takes effect. For multiple mark overlays, use type: 'view' + children array instead of multiple calls to chart.options()
encode object: encode: { x, y } (V4's .position('x*y') is prohibited)
transform must be array: transform: [{ type: 'stackY' }]
labels is plural: Use labels: [{ text: 'field' }] not label: {}
coordinate rules:
- Coordinate type should be written directly:
coordinate: { type: 'theta' }, coordinate: { type: 'polar' }
transpose is a transformation, not a coordinate type, and must be written in the transform array: coordinate: { transform: [{ type: 'transpose' }] }
- ❌ Prohibited:
coordinate: { type: 'transpose' }
- Range encoding (Gantt chart, candlestick, etc.):
encode: { y: 'start', y1: 'end' }, prohibit y: ['start', 'end']
- Style principles: Styles mentioned in the user description (radius, fillOpacity, color, fontSize, etc.) must be fully preserved; decorative styles not mentioned by the user (shadowBlur, shadowColor, shadowOffsetX/Y, etc.) should not be added manually
animate rules: Do not add animate configuration when the user does not explicitly request animation (G2 comes with default animations), only add when the user explicitly describes animation requirements
scale.color.palette can only use valid values: Palette is looked up through d3-scale-chromatic, invalid names will throw an Unknown palette error. Do not infer or create non-existent names (e.g., 'blueOrange', 'redGreen', 'hot', 'jet', 'coolwarm' are all invalid). Common valid values: sequential palettes 'blues'|'greens'|'reds'|'ylOrRd'|'viridis'|'plasma'|'turbo'; diverging palettes 'rdBu'|'rdYlGn'|'spectral'; when in doubt, use range: ['#startColor', '#endColor'] for custom alternatives
- Prohibit using
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. For aggregation, prioritize using G2 built-in options (e.g., sortX's reducer: 'sum'), when custom aggregation is necessary, 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))
- When the user does not specify a color scheme, prohibit using white or near-white as the shape fill color:
style: { fill: '#fff' }, style: { fill: 'white' }, style: { fill: '#ffffff' } etc. will make the shape completely invisible on a 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 (e.g., '#5B8FF9'). The following are valid exceptions: label text fill: '#fff' (labels within dark backgrounds), separator line stroke: '#fff' (white separator lines in stacked/pack/treemap charts)
padding only accepts number | 'auto', array form is prohibited: padding: [40, 30, 40, 50] is invalid in G2 v5 (will be ignored or throw an error). For uniform padding, use padding: 40; for directional control, use paddingTop / paddingRight / paddingBottom / paddingLeft separately; default 'auto' automatically reserves space for axes/legends, manual configuration is usually not needed. Prohibit setting padding: 0—this will disable automatic calculation, causing axes/legends to be truncated; when adjusting only one direction, set the corresponding direction separately
- When
autoFit: true, prohibit setting width simultaneously: autoFit will completely ignore width, when both are present, width is invalid. With autoFit: true, set only height; when fixed width and height are needed, remove autoFit and use width + height instead
- When the user does not specify a container:
container defaults to 'container', do not create using document.createElement('div'), the code must end with chart.render();
- Prohibit storing hex color values in data and mapping through
encode.color: When encode.color maps to a field containing hex strings (e.g., '#1e3a5f'), the Ordinal scale will treat the hex string as a "category key" rather than a color value—the final rendered color comes from G2's default palette instead of the hex value in the data, and the legend will display meaningless hex strings. Correct approach: remove the color field from the data, place the hex color value in scale.color.range, let encode.color point to a field with business meaning (e.g., 'group'), and use scale.color.domain + range for precise pairing. Exception: If dynamic colors from the data must be used directly, explicitly configure scale: { color: { type: 'identity' } }
- Label visibility and anti-overlapping: For bar chart labels with
position: 'inside', must add transform: [{ type: 'contrastReverse' }]; for data-dense charts (multi-series line charts, scatter plots, grouped bar charts), labels must add overlapDodgeY or overlapHide; for labels in marks with limited space (stacked charts, TreeMap, Sunburst), must add overflowHide; prohibit using dx to offset label positioning, use position to control position instead. See Label Configuration for details
- Text contrast on dark backgrounds: When the container background is dark/black, must use
theme: 'classicDark' (or theme: { type: 'classicDark', view: { viewFill: 'color value' } }), G2 will automatically switch all component text to light colors; on light backgrounds, prohibit setting text to light gray (e.g., labelFill: '#ccc'); in pie charts, scale.color.range must not contain colors identical or similar to the background. See Dark Theme Adaptation for details
1.1 Forbidden Patterns
Forbidden: Using V4 Syntax, must use V5 Spec Mode:
const view = chart.createView();
view.options({...});
chart.interval()
.data([...])
.encode('x', 'genre')
.encode('y', 'sold')
.style({ radius: 4 });
chart.line().encode('x', 'date').encode('y', 'value');
chart.source(data);
chart.interval().position('genre*sold');
chart.options({
type: 'interval',
data: [...],
encode: { x: 'genre', y: 'sold' },
style: { radius: 4 },
});
Reason: V5 uses Spec Mode, which has a clear structure and is easy to serialize, dynamically generate, and debug.
Correct V5 Alternative for createView
chart.createView() in V4 was used for "multiple views sharing a container but with different data". In V5, it corresponds to two scenarios:
Scenario A: Multiple marks stacked within the same coordinate system (most common)
→ Use type: 'view' + children array, children cannot nest view or children:
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 side by side or stacked (e.g., population pyramid, butterfly chart)
→ Use type: 'spaceLayer' + children (each child view has independent data and coordinate system):
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) },
},
});
Selection Principle:
- If both sides have the same data structure but opposite directions → Prioritize negative value trick (single
interval, most concise code)
- If both sides require completely independent coordinate systems/scales → Use
spaceLayer
1.2 Prohibited Hallucinated Mark Types
The following types are from other chart libraries (such as ECharts, Vega) and do not exist in G2. Using them will result in runtime errors:
| ❌ Incorrect Usage | ✅ Correct Replacement |
|---|
type: 'ruleX' | type: 'lineX' (vertical reference line) |
type: 'ruleY' | type: 'lineY' (horizontal reference line) |
type: 'regionX' | type: 'rangeX' (X-axis range highlight) |
type: 'regionY' | type: 'rangeY' (Y-axis range highlight) |
type: 'venn' | type: 'path' + data.transform: [{ type: 'venn' }] |
Complete List of Valid Mark Types in G2 (do not create other types arbitrarily):
- 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 define a 2D rectangle, and the x/y fields of the data must be [start, end] arrays)
- Statistical:
box, boxplot, density, heatmap, beeswarm
- Hierarchy/Relationship:
treemap, pack, partition, tree, sankey, chord
- Special:
wordCloud, gauge, liquid
- Requires Extension Package:
sunburst (requires @antv/g2-extension-plot, see Sunburst Chart)
2. Common Mistakes
⚠️ Most Frequent Error: Prohibit Multiple Calls to chart.options()
chart.options() is a full replacement, not a merge. When called multiple times, only the last call takes effect, and all previous configurations are lost. Each chart can only call chart.options() once.
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' } });
chart.options({
type: 'view',
data,
children: [
{ type: 'interval', encode: { x: 'x', y: 'y' } },
{ type: 'line', encode: { x: 'x', y: 'y' } },
{ type: 'text', encode: { x: 'x', y: 'y', text: 'label' } },
],
});
chart.options({
type: 'view',
data: mainData,
children: [
{ type: 'interval', encode: { x: 'x', y: 'y' } },
{ type: 'text', data: labelData, encode: { x: 'x', text: 'label' } },
],
});
Multi-mark combination rules:
- Only use
children, prohibit marks, layers, etc.
children cannot be nested (children cannot contain type: 'view' + children)
- Use
spaceLayer/spaceFlex for complex multi-coordinate system combinations
chart.options({ type: 'view', data, marks: [...] });
chart.options({ type: 'view', data, Layers: [...] });
chart.options({ type: 'view', children: [{ type: 'view', children: [...] }] });
chart.options({
type: 'spaceLayer',
children: [
{ type: 'view', children: [...] },
{ type: 'line', encode: { x: 'x', y: 'y' } },
],
});
Other Common Errors
const chart = new Chart({ container: 'container', padding: [40, 30, 40, 50] });
const chart = new Chart({ container: 'container', padding: 40 });
const chart = new Chart({ container: 'container', paddingTop: 40, paddingLeft: 60 });
const chart = new Chart({ width: 640, height: 480 });
const chart = new Chart({ container: 'container', width: 640, height: 480 });
chart.options({ transform: { type: 'stackY' } });
chart.options({ transform: [{ type: 'stackY' }] });
chart.options({ label: { text: 'value' } });
chart.options({ labels: [{ text: 'value' }] });
chart.options({
labels: [{ text: 'value', formatter: (d) => d.value + '%' }],
});
chart.options({
labels: [{ text: (d) => d.value + '%' }],
});
chart.options({
labels: [{ text: 'value', formatter: (val) => val + '%' }],
});
const barData = [
{ group: 'Legal Professionals', value: 85, color: '#1e3a5f' },
{ group: 'Corporate Governance Experts', value: 78, color: '#2d4a6f' },
];
chart.options({
type: 'interval',
data: barData,
encode: { x: 'group', y: 'value', color: 'color' },
scale: { color: { type: 'ordinal' } },
});
chart.options({
type: 'interval',
data: [
{ group: 'Legal Professionals', value: 85 },
{ group: 'Corporate Governance Experts', value: 78 },
],
encode: { x: 'group', y: 'value', color: 'group' },
scale: {
color: {
type: 'ordinal',
domain: ['Legal Professionals', 'Corporate Governance Experts'],
range: ['#1e3a5f', '#2d4a6f'],
},
},
});
chart.options({
type: 'interval',
data: [
{ group: 'Legal Professionals', value: 85, color: '#1e3a5f' },
{ group: 'Corporate Governance Experts', value: 78, color: '#2d4a6f' },
],
encode: { x: 'group', y: 'value', color: 'color' },
scale: {
color: { type: 'identity' },
},
});
chart.options({
type: 'area',
data,
encode: { x: 'date', y: 'value' },
style: { fill: '#FF5924', fillOpacity: 0.4, stroke: '#FF5924', lineWidth: 2 },
});
chart.options({
type: 'view',
data,
children: [
{ type: 'area', encode: { x: 'date', y: 'value' }, style: { fill: '#FF5924', fillOpacity: 0.4 } },
{ type: 'line', encode: { x: 'date', y: 'value' }, style: { stroke: '#FF5924', lineWidth: 2 } },
],
});
chart.options({ scale: { x: { type: 'linear' }, y: { type: 'linear' } } });
chart.options({ scale: { y: { domain: [0, 100] } } });
3. Basic Structure
import { Chart } from '@antv/g2';
const chart = new Chart({ container: 'container', width: 640, height: 480 });
chart.options({
type: 'interval',
data: [...],
encode: { x: 'field', y: 'field', color: 'field' },
transform: [],
scale: {},
coordinate: {},
style: {},
labels: [],
tooltip: {},
axis: {},
legend: {},
});
chart.render();
4. Core Concepts
Core concepts are the foundation of G2, and understanding them is a prerequisite for using G2 correctly.
4.1 Chart Initialization
Chart is the core class of G2, and all charts start from a Chart instance.
import { Chart } from '@antv/g2';
const chart = new Chart({
container: 'container',
width: 640,
height: 480,
autoFit: true,
padding: 'auto',
theme: 'light',
});
Detailed Documentation: Chart Initialization
4.2 encode Channel System
encode maps data fields to visual channels and is a core concept in G2.
| Channel | Usage | Example |
|---|
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 Composition (view + children)
Use the view type in conjunction with the children array to compose multiple marks.
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 / Concept Guide
The concept guide helps in selecting the correct chart type and configuration scheme.
5.1 Chart Selection
Select the appropriate chart type based on data characteristics and visualization goals:
| Data Relationship | Recommended Chart | Mark |
|---|
| Comparison | Bar Chart, Column Chart | interval |
| Trend | Line Chart, Area Chart | line, area |
| Proportion | Pie Chart, Ring Chart | interval + theta |
| Distribution | Histogram, Box Plot | rect, boxplot |
| Correlation | Scatter Plot, Bubble Chart | point |
| Hierarchy | Treemap, Partition Chart, Sunburst Chart | treemap, partition, sunburst (requires extension package) |
Detailed Documentation: Chart Selection Guide
5.2 Visual Channels / Visual Channels
Visual channels are the mapping methods from data to visual attributes:
| Channel Type | Suitable Data | Perceptual Accuracy |
|---|
| Position | Continuous/Discrete | Highest |
| Length | Continuous | High |
| Color (Hue) | Discrete | Medium |
| Color (Luminance) | Continuous | Medium |
| Size | Continuous | Medium-Low |
| Shape | Discrete | Low |
Detailed Documentation: Visual Channels
5.3 Color Theory
Selecting an appropriate color scheme enhances chart readability:
| Scenario | Recommended Scheme | Example |
|---|
| Categorical Data | Discrete Palette | category10, category20 |
| Sequential Data | Sequential Palette | Blues, RdYlBu |
| Positive/Negative Contrast | Diverging Palette | RdYlGn |
Detailed Documentation: Color Theory
6. Marks / Chart Types
Marks are the core visualization elements in G2, determining the visual representation of data. Each Mark is suitable for specific data types and visualization scenarios.
6.1 Bar Chart Series / Interval
Bar charts are used to compare the magnitude of categorical data and are one of the most commonly used chart types. Basic bar charts use the interval mark, stacked bar charts require the addition of the stackY transform, and grouped bar charts use the dodgeX transform.
| Type | Mark | Key Configuration |
|---|
| Basic Bar Chart | interval | - |
| Stacked Bar Chart | interval | transform: [{ type: 'stackY' }] |
| Grouped Bar Chart | interval | transform: [{ type: 'dodgeX' }] |
| Percentage 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 | Percentage Bar Chart
6.2 Line Chart Series / Line
Line charts are used to display the trend of data changes over time or ordered categories. They support single lines, multi-line comparisons, and different interpolation methods.
| Type | Mark | Key Configuration |
|---|
| Basic Line Chart | line | - |
| Multi-Series Line | line | encode: { color: 'category' } |
| Smooth Curve | line | encode: { shape: 'smooth' } |
| Step Line | line | encode: { shape: 'step' } |
Detailed Documentation: Basic Line Chart | Multi-Series Line | LineX/LineY
6.3 Area Series / Area
Area charts build upon line charts by filling the area beneath the line, emphasizing the magnitude of change over time. Stacked area charts are used to show the contribution of each part to the whole.
| Type | Mark | Key Configuration |
|---|
| Basic Area Chart | area | - |
| Stacked Area Chart | area | transform: [{ type: 'stackY' }] |
Detailed Documentation: Basic Area Chart | Stacked Area Chart
6.4 Pie Chart/Donut Chart / Arc (Pie/Donut)
Pie charts are used to display the proportion of each part to the whole. They are implemented using the theta coordinate system in conjunction with the interval mark.
| Type | Mark | Key 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 Scatter Plot/Bubble Plot / Point
Scatter plots are used to display the relationship between two numerical variables, while bubble plots use the size of the points to represent a third dimension.
| Type | Mark | Key Configuration |
|---|
| Scatter Plot | point | encode: { x, y } |
| Bubble Plot | point | encode: { x, y, size } |
Detailed Documentation: Scatter Plot | Bubble Plot
6.6 Histogram
Histograms are used to display the distribution of continuous numerical data, implemented using the rect mark with the binX transform. Unlike bar charts, histograms have no gaps between bars, representing continuous data.
| Type | Mark | Key Configuration |
|---|
| Basic Histogram | rect | transform: [{ type: 'binX', y: 'count' }] |
| Multi-Distribution Comparison | rect | groupBy grouping |
Detailed Documentation: Histogram
6.7 Rose Chart / Radial Bar Chart / Polar Charts
Charts under the polar coordinate system, representing numerical values through radius or arc length, are visually more appealing.
| Type | Mark | Key Configuration |
|---|
| Rose Chart | interval | coordinate: { type: 'polar' } |
| Radial Bar Chart | interval | coordinate: { type: 'radial' } |
Detailed Documentation: Rose Chart | Radial Bar Chart
6.8 Distribution
Charts that display data distribution characteristics, suitable for statistical analysis and exploratory data analysis.
| Type | Mark | Usage |
|---|
| Boxplot | boxplot | Data distribution statistics |
| Box (Boxplot) | box | Manually specified boxplot with five-number summary |
| Density Plot | density | Kernel density estimation curve |
| Violin Plot | density + boxplot | Density distribution + statistical information |
| Distribution Curve | line + smooth | Frequency density distribution curve |
| Polygon | polygon | Custom polygon area |
| Contour Line Chart | cell + sequential color scale | Two-dimensional continuous data distribution (simulated contour lines) |
Detailed Documentation: Boxplot | Box (Boxplot) | Density Plot | Violin Plot | Distribution Curve | Contour Line Chart | Polygon
6.9 Relation
Charts that display relationships between data, suitable for network analysis and set relationship visualization.
| Type | Mark | Use Case |
|---|
| Sankey Diagram | sankey | Flow/transfer relationships |
| Chord Diagram | chord | Matrix flow relationships |
| Venn Diagram | path + venn data transform | Set intersection relationships (venn is a data transform, not a mark type) |
| Arc Diagram | line + point | Node link relationships |
Detailed Documentation: Sankey Diagram | Chord Diagram | Venn Diagram | Arc Diagram
6.10 Project Management Charts / Project
Charts suitable for project management and progress tracking.
| Type | Mark | Use Case |
|---|
| Gantt Chart | interval | Task scheduling |
| Bullet Chart | interval + point | KPI metric display |
Detailed Documentation: Gantt Chart | Bullet Chart
6.11 Finance
Professional charts for financial data analysis.
| Type | Mark | Usage |
|---|
| K-line Chart | link + interval | Stock four-price data |
Detailed Documentation: K-line Chart
6.12 Multivariate Data Chart / Multivariate
Charts for displaying multivariate data relationships.
| Type | Mark | Use Case |
|---|
| Parallel Coordinates | line | Multivariate data relationship analysis |
| Radar Chart | line | Multivariate data comparison |
Detailed Documentation: Parallel Coordinates | Radar Chart
6.13 Comparison Chart
Suitable for data comparison.
| Type | Mark | Usage |
|---|
| Bi-directional Bar Chart | interval | Positive and negative data comparison |
| Funnel Chart | interval + shape:'funnel' | Business conversion rate display |
| Mosaic Chart | interval/cell + transform | Two-dimensional categorical distribution |
Detailed Documentation: Bi-directional Bar Chart | Funnel Chart | Mosaic Chart
6.14 Basic Marks
Basic marks are the fundamental building blocks of G2, which can be used independently or combined to construct complex charts.
| Type | Mark | Usage |
|---|
| Rectangle | rect | Rectangular area, basis for histograms/heatmaps |
| Text | text | Text annotations and labels |
| Image | image | Image mark, representing data points with images |
| Path | path | Custom path drawing |
| Link | link | Line connecting two points |
| Connector | connector | Connection line between data points |
| Shape | shape | Custom shape drawing |
| Vector | vector | Vector/arrow mark, for wind field charts, etc. |
Detailed Documentation: rect | text | image | path | link | connector | shape | vector
6.15 Range Mark / Range
The range mark is used to display the interval range of data.
| Type | Mark | Usage |
|---|
| Time Period/Interval Highlight (X Direction) | rangeX | X-axis interval, encode: { x: 'start', x1: 'end' } |
| Numerical Range Highlight (Y Direction) | rangeY | Y-axis interval, encode: { y: 'min', y1: 'max' } |
| Two-Dimensional 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
| Type | Mark | Usage |
|---|
| Beeswarm Plot | point + pack | Closely arranged data points to display distribution |
| Pack Layout | pack | Circular packing for hierarchical data |
Detailed Documentation: Beeswarm Plot | Pack Layout
6.17 Hierarchy
Charts for displaying hierarchical data, representing numerical proportions through area or radius.
| Type | Mark | Usage |
|---|
| Treemap | treemap | Hierarchical data proportion |
| Sunburst | sunburst⚠️ | Multi-level concentric circle display (requires @antv/g2-extension-plot) |
| Partition | partition | Hierarchical data partition display |
| Tree | tree | Tree-like hierarchical structure |
Detailed Documentation: Treemap | Sunburst | Partition | Tree
6.18 Other Charts / Others
| Type | Mark | Usage |
|---|
| Heatmap | cell | Visualization of two-dimensional matrix data |
| Density Heatmap | heatmap | Continuous density heatmap |
| Gauge | gauge | Metric progress display |
| Word Cloud | wordCloud | Text frequency visualization |
| Liquid Fill Gauge | liquid | Percentage progress |
| Spiral Plot | line/interval + helix coordinate system | Periodic patterns of large time series |
Detailed Documentation: Heatmap | Density Heatmap | Gauge | Word Cloud | Liquid Fill Gauge | Spiral Plot
7. Data / Data Transformation
Data transformation is performed during the data loading stage and is configured in data.transform, affecting all marks that use this data.
7.1 Data Transform Types (Configured in data.transform)
| Transform | Type | Purpose | Example Scenario |
|---|
| fold | fold | Wide table to long table | Convert multi-column data to multiple series |
| filter | filter | Filter data by condition | Filter invalid data |
| sort | sort | Sort using a callback function | Custom sorting logic |
| sortBy | sortBy | Sort by field | Sort by field value |
| map | map | Data mapping transformation | Add computed fields |
| join | join | Merge data tables | Associate external data |
| pick | pick | Select specified fields | Simplify fields |
| rename | rename | Rename fields | Field renaming |
| slice | slice | Slice data range | Pagination/slicing |
| ema | ema | Exponential Moving Average | Time series smoothing |
| kde | kde | Kernel Density Estimation | Density plot/violin plot |
| log | log | Print data to console | Debugging |
| custom | custom | Custom data processing | Complex transformations |
7.2 Data Format and Patterns
| Type | Purpose |
|---|
| Tabular Data Format | Description of the standard tabular data format accepted by G2 |
| Data Transformation Patterns | Combined usage patterns of Data Transform and Mark Transform |
Detailed Documentation: filter | sort | sortBy | fold | slice | ema | kde | log | fetch | Data Transformation Patterns
7.3 Common Mistakes: Incorrect Placement of Data Transform
chart.options({
type: 'interval',
data: wideData,
transform: [{ type: 'fold', fields: ['a', 'b'] }],
});
chart.options({
type: 'interval',
data: {
type: 'inline',
value: wideData,
transform: [{ type: 'fold', fields: ['a', 'b'] }],
},
transform: [{ type: 'stackY' }],
});
7.4 Combination Example: Wide Table Data + Stacked Chart
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: [
{ type: 'fold', fields: ['Type A', 'Type B', 'Type C'], key: 'type', value: 'value' },
],
},
encode: { x: 'year', y: 'value', color: 'type' },
transform: [
{ type: 'stackY' },
],
coordinate: { type: 'polar' },
});
8. Transforms / Mark Transformations
Mark transformations are executed when binding visual channels and are configured in the transform array of the mark. They are used for data aggregation, anti-overlapping, and other purposes.
Configuration Location: The transform array, which is at the same level as data and encode, not in data.transform.
chart.options({
type: 'interval',
data,
encode: { x: 'category', y: 'value', color: 'type' },
transform: [
{ type: 'stackY' },
{ type: 'sortX', by: 'y' },
],
});
8.1 Anti-overlap Transformations
| Transformation | Type | Purpose |
|---|
| Stack | stackY | Data stacking, used for stacked charts |
| Dodge | dodgeX | Data grouping, used for dodged charts |
| Jitter | jitter | Scatter jitter to avoid overlap |
| Jitter X | jitterX | Jitter in the X direction |
| Jitter Y | jitterY | Jitter in the Y direction |
| Pack | pack | Tightly arrange data points |
Detailed Documentation: stackY | dodgeX | jitter | jitterX | jitterY | pack
8.2 Aggregation Transforms / Aggregation
| Transform | Type | Purpose |
|---|
| General Grouping | group | General grouping aggregation |
| Group Aggregation | groupX / groupY | Group and aggregate by dimension |
| Group Color | groupColor | Group aggregation by color |
| Binning | bin | Two-dimensional binning |
| X-Axis Binning | binX | Binning in the X-axis direction |
| Sampling | sample | Data sampling |
Detailed Documentation: group | groupX | groupY | groupColor | bin | binX | sample
8.3 Sorting Transforms / Sorting
| Transform | Type | Purpose |
|---|
| X-axis Sorting | sortX | Sort by X channel |
| Y-axis Sorting | sortY | Sort by Y channel |
| Color Sorting | sortColor | Sort by color channel |
Detailed Documentation: sortX | sortY | sortColor
8.4 Selection Transforms / Selection
| Transform | Type | Purpose |
|---|
| Select | select | Global data selection |
| Select X | selectX | Selection by X grouping |
| Select Y | selectY | Selection by Y grouping |
Detailed Documentation: select | selectX | selectY
8.5 Other Transforms / Others
| Transform | Type | Usage |
|---|
| Normalize | normalizeY | Y-axis normalization |
| Difference | diffY | Calculate differences |
| Symmetry | symmetryY | Y-axis symmetry |
| Flex X | flexX | X-axis flex layout |
| Stack Enter | stackEnter | Stacked enter animation |
Detailed Documentation: normalizeY | diffY | symmetryY | flexX | stackEnter
9. Interactions
G2 provides a rich set of built-in interactions for data exploration and chart manipulation.
9.1 Selection Interactions
| Interaction | Type | Purpose |
|---|
| Element Selection | elementSelect | Click to select data elements |
| Conditional Selection | elementSelectBy | Batch select elements based on conditions |
| Brush Selection | brush / brushX / brushY | Rectangular area selection |
| 2D Brush Selection | brushXY | Simultaneous XY brush selection |
| Axis Brush Selection | brushAxis | Coordinate axis range selection |
| Legend Filter | legendFilter | Click legend to filter data |
Detailed Documentation: elementSelect | elementSelectBy | brush | brushXY | brushAxis | legendFilter
9.2 Highlight Interactions / Highlight
| Interaction | Type | Purpose |
|---|
| Element Highlight | elementHighlight | Hover to highlight elements |
| Conditional Highlight | elementHighlightBy | Batch highlight elements based on conditions |
| Hover Scale | elementHoverScale | Scale up elements on hover |
| Legend Highlight | legendHighlight | Highlight corresponding elements on legend hover |
| Brush Highlight | brushXHighlight / brushYHighlight | Highlight elements in the brushed area |
Detailed Documentation: elementHighlight | elementHighlightBy | elementHoverScale | legendHighlight | brushXHighlight | brushYHighlight | Single-Axis Brush Highlight
9.3 Filter Interactions / Filter
| Interaction | Type | Purpose |
|---|
| Slider Filter | sliderFilter | Filter data range using a slider |
| Scrollbar Filter | scrollbarFilter | Filter data using a scrollbar |
| Brush Filter | brushFilter | Filter data within a selected area |
| X-Axis Brush Filter | brushXFilter | Filter data along the X-axis direction |
| Y-Axis Brush Filter | brushYFilter | Filter data along the Y-axis direction |
| Adaptive Filter | adaptiveFilter | Adaptively filter data |
Detailed Documentation: sliderFilter | scrollbarFilter | brushFilter | brushXFilter | brushYFilter | adaptiveFilter
9.4 Other Interactions / Others
| Interaction | Type | Purpose |
|---|
| Tooltip | tooltip | Display data details on hover |
| Pop-up Tip | poptip | Concise pop-up tip |
| Drill Down | drilldown | Hierarchical data drill down |
| Treemap Drill Down | treemapDrilldown | Treemap hierarchical drill down |
| Zoom | fisheye | Fish-eye magnifier effect |
| Scroll Wheel | sliderWheel | Mouse wheel controls the slider |
| Drag and 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 / 组件
Components are auxiliary elements of charts, such as axes, legends, and tooltips.
10.1 Axis
The axis displays data dimensions and supports rich style configurations.
Detailed Documentation: Axis Configuration | Radar Chart Axis
10.2 Legend
The legend displays data categorization or continuous value mapping, supporting categorical legends and continuous legends (color ramps).
| Type | Purpose |
|---|
| Categorical Legend | Color mapping explanation for discrete categorical data |
| Continuous Legend | Color/size mapping explanation for continuous values (color ramp) |
Detailed Documentation: Legend Configuration | Categorical Legend | Continuous Legend
10.3 Tooltip
Tooltip displays data details on hover and supports custom templates and formatting.
Detailed Documentation: Tooltip Configuration
10.4 Other Components / Others
| Component | Purpose |
|---|
| Title | Chart title |
| Label | Data label |
| Scrollbar | Data scrolling |
| Slider | Data range selection |
| Annotation | Data annotation and auxiliary lines |
Detailed Documentation: Title | Label | Scrollbar | Slider | Annotation
11. Scales
Scales map data values to visual channels such as position, color, size, and more.
11.1 ⚠️ Default Behavior (Avoid Over-Specifying type)
G2 automatically infers the scale type based on the data type. Avoid manually specifying type unless necessary:
| Data Type | Inferred Scale | Example |
|---|
| Numerical Field | linear | { value: 100 } → linear |
| Categorical Field | band | { category: 'A' } → band |
| Date Object | time | { date: new Date() } → time |
chart.options({
scale: {
x: { type: 'linear' },
y: { type: 'linear' },
},
});
chart.options({
scale: {
y: { domain: [0, 100] },
color: { range: ['#1890ff', '#52c41a'] },
},
});
Special Cases Requiring Manual type Specification:
| Scenario | Type | Description |
|---|
| Logarithmic Scale | log | Data spanning multiple orders of magnitude |
| Power Scale | pow | Non-linear data mapping |
| Square Root Scale | sqrt | Compression of non-negative data |
| String Date | time | Date field is a string, not a Date object |
| Custom Mapping | ordinal | Discrete value to discrete value |
| Gradient Color | sequential | Continuous value to color gradient |
| Threshold Mapping | threshold | Segmented mapping to colors based on thresholds |
| Equal Interval Segmentation | quantize / quantile | Discretization of continuous data |
11.2 Scale Types
| Scale | Type | Usage |
|---|
| Linear | linear | Continuous numerical 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 value mapping |
| Sequential | sequential | Continuous value to color gradient |
| Quantile/Quantize | quantile / quantize | Continuous data discretization mapping |
| Threshold | threshold | Segmented mapping by threshold |
Detailed Documentation: linear | band | point | time | log | pow/sqrt | ordinal | sequential | quantile/quantize | threshold
12. Coordinates / 坐标系
The coordinate system defines the mapping method from data to canvas position, and different coordinate systems produce different chart forms.
| Coordinate System | Type | Usage |
|---|
| Cartesian | cartesian | Rectangular coordinate system (default) |
| Polar | polar | Radar chart, Rose chart |
| Theta | theta | Pie chart, Donut chart |
| Radial | radial | Radial coordinate system, Gauge 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 / Composition Views
Composition views are used to create multi-chart layouts, such as facets, multi-view overlays, etc.
| Composition | Type | Purpose |
|---|
| Basic View | view | Single view container, combining multiple marks |
| Facet Rect | facetRect | Split rectangular grid multi-chart by dimension |
| Facet Circle | facetCircle | Split circular multi-chart 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 |
| Geo Path | geoPath | Geographic path rendering |
Detailed Documentation: view | facetRect | facetCircle | repeatMatrix | spaceLayer | spaceFlex | timingKeyframe | geoView | geoPath
14. Themes / 主题
Themes define the overall visual style of a chart, including colors, fonts, spacing, and more.
Detailed Documentation: Built-in Themes | Custom Themes
15. Palettes
Palettes define color sequences, used for color mapping of categorical or continuous data.
Detailed Documentation: category10 | category20
16. Animations
Animations enhance the expressiveness of charts, supporting entrance, update, and exit animation configurations.
⚠️ Important Rule: G2 comes with default animation effects at the underlying level. Do not add animate configurations unless the user explicitly requests animations. Only when the user clearly describes animation requirements (e.g., "fade-in animation", "wave entrance", etc.) should you refer to the documentation and add the corresponding animate configuration.
Detailed Documentation: Animation Introduction | Animation Types | Keyframe Animation
17. Label Transforms
Label transforms are used to handle issues such as label overlap and overflow, improving label readability.
| Transform | Type | Purpose |
|---|
| Overflow Hide | overflowHide | Hide labels that exceed the area |
| Overlap Hide | overlapHide | Automatically hide overlapping labels |
| Overlap Dodge Y | overlapDodgeY | Offset overlapping labels in the Y direction |
| Contrast Reverse | contrastReverse | Automatically reverse label colors to ensure contrast |
| Exceed Adjust | exceedAdjust | Adjust the position of labels that exceed the canvas boundaries |
| Overflow Stroke | overflowStroke | Add stroke marks to overflow areas |
Detailed Documentation: overflowHide | overlapHide | overlapDodgeY | contrastReverse | exceedAdjust | overflowStroke
18. Patterns / 模式
Patterns are best practices for common scenarios, including migration guides, performance optimization, responsive adaptation, and more.
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: [{}] |
Detailed Documentation: v4 → v5 Migration
18.2 Performance Optimization / Performance
Data pre-aggregation, LTTB downsampling, Canvas renderer confirmation, high-frequency real-time data throttling updates.
| Scenario | Data Volume | Recommended Solution |
|---|
| Line Chart | < 1,000 points | Direct rendering |
| Line Chart | 1,000 ~ 10,000 points | Downsample to within 500 points |
| Line Chart | > 10,000 points | Backend aggregation + time range filtering |
| Scatter Chart | < 5,000 points | Direct rendering |
| Scatter Chart | 5,000 ~ 50,000 points | Canvas rendering + downsampling |
Detailed Documentation: Performance Optimization
18.3 Responsive
autoFit adaptive, ResizeObserver dynamic adjustment, mobile font/margin adaptation.
Detailed Documentation: Responsive Adaptation