| name | antv-g6-graph |
| description | G6 v5 graph visualization code generation skill, supporting initialization, layout, interaction, and plugin configuration for various graph types such as network graphs, tree graphs, and flowcharts |
G6 v5 Graph Visualization Code Generation Skills
Core Constraints (Must Comply)
Initialization Specifications
container parameter is required, pass in a DOM element ID string or a DOM element object
- Use
new Graph({...}) constructor, do not use new G6.Graph() (v4 syntax)
- All configurations must be completed in the constructor at once, do not override them later with multiple configuration method calls
graph.render() returns a Promise, rendering asynchronously; if you need to wait for completion, use await graph.render()
Data Structure Specification
- Data format:
{ nodes: [...], edges: [...], combos?: [...] }
- Each node must have a unique
id (string); business data is stored in the data field
- Edges must have
source and target, with values being node ids
- Prohibited: Using the v4
graph.data() method to pass data
Node/Edge Style Specifications
- Styles are configured via
node.style / edge.style, supporting both static values and callback functions
- Callback function signature:
(datum: NodeData | EdgeData) => value
- Label text is set via
style.labelText (not label or labelCfg)
- Node size is set via
style.size (a single numeric value or a [width, height] array)
Layout Specifications
layout configuration is placed in Graph options: { type: 'force', ... }
force layout does not support preventOverlap / nodeSize (G6 v4 parameters, silently ignored in v5); for overlap prevention, use d3-force + collide instead
- Tree layouts (mindmap, compact-box, dendrogram, indented) require tree data or
treeToGraphData() conversion
- Force-directed layouts run asynchronously and continue iterating after
graph.render()
nodeStrength must be a non-negative number (≥ 0); negative values will cause layout calculation errors or unpredictable node behavior
Interaction Behavior Specifications
behaviors is a string array or an array of configuration objects
- Common behavior string abbreviations:
'drag-canvas', 'zoom-canvas', 'drag-element', 'click-select'
- G6 v5 removed the Mode concept, all behaviors are configured directly in the array
- Complex configurations use object form:
{ type: 'click-select', multiple: true }
Plugin Specifications
plugins is an array, similar to behaviors
- Shorthand:
'minimap', 'grid-line', 'tooltip'
- Complex configuration:
{ type: 'tooltip', getContent: (e, items) => '...' }
Prohibited Error Patterns
❌ Using v4 API
const graph = new G6.Graph({ ... });
graph.data(data);
graph.render();
graph.node((node) => ({ ... }));
const graph = new Graph({
container: 'container',
data: { nodes: [...], edges: [...] },
node: { style: { ... } },
});
graph.render();
❌ Incorrect Node Data Structure
{ id: 'node1', label: 'Node 1', value: 100 }
{ id: 'node1', data: { label: 'Node 1', value: 100 } }
❌ Incorrect Label Configuration
node: {
labelCfg: { style: { fill: '#333' } }
}
node: {
style: {
labelText: (d) => d.data.label,
labelFill: '#333',
labelFontSize: 14,
}
}
❌ behaviors Using the Mode Concept
modes: {
default: ['drag-canvas', 'zoom-canvas'],
edit: ['create-edge'],
}
behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'],
❌ Reading attributes.data in Custom Node render() → Blank Screen
render(attributes, container) {
const { data } = attributes;
const fill = data.color;
}
node: {
type: 'my-node',
style: { color: (d) => d.data.color },
},
render(attributes, container) {
const { color = '#1783FF' } = attributes;
}
❌ Using extend to Register Custom Nodes
import { Graph, extend } from '@antv/g6';
const extendedGraph = extend(Graph, {
nodes: { 'my-node': MyNodeFn },
});
const MyNode = (node) => (model) => {
const group = node.group();
group.addShape('circle', { attrs: { r: 20 } });
};
import { BaseNode, Circle, ExtensionCategory, Graph, register } from '@antv/g6';
class MyNode extends BaseNode {
render(attributes, container) {
super.render(attributes, container);
this.upsert('key', Circle, { cx: 0, cy: 0, r: 20, fill: '#1783FF' }, container);
}
}
register(ExtensionCategory.NODE, 'my-node', MyNode);
const graph = new Graph({ node: { type: 'my-node' } });
❌ Missing container
const graph = new Graph({ });
const graph = new Graph({ container: 'container' });
const graph = new Graph({ container: document.getElementById('container') });
Common variant error: container: container (using a string ID as a variable name, variable is undefined → ReferenceError → blank screen)
❌ autoFit: 'view' with Asynchronous Force-Directed Layout Causes Blank Screen
const graph = new Graph({
autoFit: 'view',
layout: { type: 'combo-combined' },
});
graph.render();
import { Graph, GraphEvent } from '@antv/g6';
const graph = new Graph({
layout: { type: 'combo-combined' },
});
graph.on(GraphEvent.AFTER_LAYOUT, () => graph.fitView({ padding: 20 }));
graph.render();
Synchronous layouts (dagre, grid, circular, etc.) are not affected by this issue and can directly use autoFit: 'view'.
Basic Structure Template
import { Graph } from '@antv/g6';
const graph = new Graph({
container: 'container',
autoFit: 'view',
data: {
nodes: [
{ id: 'n1', data: { label: 'Node 1' } },
{ id: 'n2', data: { label: 'Node 2' } },
],
edges: [
{ source: 'n1', target: 'n2' },
],
},
node: {
type: 'circle',
style: {
size: 40,
fill: '#1783FF',
stroke: '#fff',
lineWidth: 2,
labelText: (d) => d.data.label,
labelPlacement: 'bottom',
},
},
edge: {
type: 'line',
style: {
stroke: '#aaa',
lineWidth: 1,
endArrow: true,
},
},
layout: {
type: 'force',
preventOverlap: true,
nodeSize: 40,
},
behaviors: ['drag-canvas', 'zoom-canvas', 'drag-element'],
plugins: ['grid-line'],
theme: 'light',
});
graph.render();
Chart Type Selection Guide
| Chart Type | Recommended Layout | Typical Scenarios |
|---|
| Network/Relationship Graph | force / fruchterman | Social Networks, Knowledge Graphs |
| Hierarchical/Flow Chart | dagre / antv-dagre | Organizational Structures, Workflows |
| Tree Map | compact-box / mindmap | File Trees, Mind Maps |
| Circular Chart | circular | Circular Dependencies, Circular Relationships |
| Grid Chart | grid | Chessboard Layouts, Matrix Relationships |
| Concentric Circles | concentric | Radial Relationships |
| Radial Layout | radial | Radiation from a Specific Node |
Built-in Node Types
| Type Name | Shape | Applicable Scenarios |
|---|
circle | Circle | General nodes, network graphs |
rect | Rectangle | Flowcharts, UML |
ellipse | Ellipse | General, emphasizing vertical orientation |
diamond | Diamond | Decision nodes |
hexagon | Hexagon | Honeycomb layouts |
triangle | Triangle | Special markers |
star | Star | Special markers, ratings |
donut | Donut | Nodes with progress |
image | Image | Avatars, icon nodes |
html | HTML | Rich text custom nodes |
Built-in Edge Types
| Type Name | Shape | Applicable Scenarios |
|---|
line | Straight Line | Simple Graphs, Topology Diagrams |
cubic | Cubic Bézier Curve | General, Arched Effect |
cubic-horizontal | Horizontal Cubic Curve | Horizontal Flowcharts |
cubic-vertical | Vertical Cubic Curve | Vertical Flowcharts |
quadratic | Quadratic Bézier Curve | Lightweight Arched Edge |
polyline | Polyline | Orthogonal Layouts |
loop | Self-Loop | Node Self-Loop |
Built-in Layout Algorithms
| Layout Name | Type | Features |
|---|
force | Force-directed | Physical simulation, natural distribution |
d3-force | Force-directed | Based on D3, configurable force types |
fruchterman | Force-directed | Fast, supports GPU acceleration |
force-atlas2 | Force-directed | Large-scale graphs, good clustering effect |
dagre | Hierarchical | DAG, automatic layering |
antv-dagre | Hierarchical | AntV optimized version of Dagre |
circular | Circular | Nodes arranged in a circle |
concentric | Concentric | Rings divided by attribute values |
grid | Grid | Regular grid arrangement |
radial | Radial | Radiates from a specific node |
mds | Dimensionality Reduction | Preserves relative node distances |
random | Random | For debugging |
compact-box | Tree | Compact tree, saves space |
mindmap | Tree | Mind map style |
dendrogram | Tree | Dendrogram |
indented | Tree | Indented tree |
Built-in Interaction Behaviors
| Behavior Name | Description |
|---|
drag-canvas | Drag canvas |
zoom-canvas | Zoom canvas with mouse wheel |
scroll-canvas | Pan canvas with mouse wheel |
drag-element | Drag node/edge/combo |
drag-element-force | Drag node in force-directed graph |
click-select | Click to select element |
brush-select | Box select elements |
lasso-select | Lasso select |
hover-activate | Hover to activate element |
collapse-expand | Collapse/expand node (tree graph) |
create-edge | Interactively create edge |
focus-element | Focus on element (zoom to specified element) |
fix-element-size | Maintain element size during zoom |
auto-adapt-label | Automatically show/hide labels (prevent overlap) |
optimize-viewport-transform | Large-scale graph viewport optimization |
Built-in Plugins
| Plugin Name | Description |
|---|
grid-line | Grid background lines |
background | Background color/image |
watermark | Watermark |
minimap | Minimap navigation |
legend | Legend |
tooltip | Element tooltip |
toolbar | Toolbar (zoom, undo, etc.) |
contextmenu | Context menu |
history | Undo/Redo |
timebar | Timeline filter |
fisheye | Fisheye magnification effect |
edge-bundling | Edge bundling |
edge-filter-lens | Edge filter lens |
hull | Element contour hull |
bubble-sets | Bubble sets |
snapline | Alignment guide lines |
fullscreen | Fullscreen |
Element States (States)
G6 v5 has 5 built-in states: selected, active, highlight, inactive, disabled
node: {
style: {
fill: '#1783FF',
},
state: {
selected: {
fill: '#ff6b6b',
stroke: '#ff4d4d',
lineWidth: 3,
},
hover: {
fill: '#40a9ff',
},
},
},
graph.setElementState('node1', 'selected');
graph.setElementState('node1', ['selected', 'highlight']);
graph.setElementState('node1', []);
Theme System
const graph = new Graph({
theme: 'light',
});
graph.setTheme('dark');
graph.render();
Data Manipulation API
graph.addNodeData([{ id: 'n3', data: { label: 'New Node' } }]);
graph.addEdgeData([{ source: 'n1', target: 'n3' }]);
graph.updateNodeData([{ id: 'n1', style: { fill: 'red' } }]);
graph.removeNodeData(['n3']);
graph.draw();
Common Usage Patterns
Data-Driven Styling (Recommended)
node: {
style: {
size: (d) => d.data.size || 30,
fill: (d) => {
const colorMap = { type1: '#1783FF', type2: '#FF6B6B', type3: '#52C41A' };
return colorMap[d.data.type] || '#ccc';
},
labelText: (d) => d.data.name,
},
},
Palette Mapping
node: {
palette: {
type: 'group',
field: 'category',
color: 'tableau10',
},
},
Continuous Numerical Mapping of Node Size
transforms: [
{
type: 'map-node-size',
field: 'value',
range: [16, 60],
},
],
Parallel Edge Processing
transforms: [
{
type: 'process-parallel-edges',
offset: 15,
},
],
edge: {
type: 'quadratic',
},
Data Manipulation API Quick Reference
graph.addNodeData([{ id: 'n3', data: { label: 'New Node' } }]);
graph.addEdgeData([{ source: 'n1', target: 'n3' }]);
graph.draw();
graph.removeNodeData(['n3']);
graph.draw();
graph.updateNodeData([{ id: 'n1', data: { label: 'Updated' } }]);
graph.draw();
const node = graph.getNodeData('n1');
const selected = graph.getElementDataByState('node', 'selected');
const zoom = graph.getZoom();
await graph.fitView({ padding: 20 });
await graph.focusElement('n1', { duration: 500 });
await graph.zoomTo(1.5);
graph.setElementState('n1', 'selected');
graph.setElementState('n1', []);
graph.destroy();
Event Listening Quick Reference
graph.on('node:click', (e) => console.log(e.target.id));
graph.on('edge:pointerover', (e) => graph.setElementState(e.target.id, 'active'));
graph.on('canvas:click', () => { });
import { GraphEvent } from '@antv/g6';
graph.on(GraphEvent.AFTER_RENDER, () => console.log('Rendering complete'));
graph.on(GraphEvent.AFTER_LAYOUT, () => console.log('Layout complete'));
Reference Document Index
Core
Node Types
Combo
Edge Types
Layout
Data Transformations
Interaction Behaviors
Plugins
State and Theme
Scene Templates