Loading...
Layout is a crucial part of graph visualization, determining the positioning of nodes on the canvas. G6 offers a variety of layout algorithms to meet different data structures and visualization needs. Through the layout API, you can:
A suitable layout can clearly display the relationship patterns between nodes, enhancing the graph's readability and aesthetics.
Set the graph's layout algorithm and configuration.
⚠️ Note: Calling this function will automatically re-layout, so there's no need to call graph.layout()
separately.
setLayout(layout: LayoutOptions | ((prev: LayoutOptions) => LayoutOptions)): void;
Parameters
Parameter | Description | Type | Default | Required |
---|---|---|---|---|
layout | Layout configuration object, or a function returning a new configuration based on the previous one | LayoutOptions | ((prev: LayoutOptions) => LayoutOptions) | - | ✓ |
Example 1: Set a force-directed layout
// Set a simple force-directed layoutgraph.setLayout({type: 'force',preventOverlap: true, // Prevent node overlapnodeStrength: -50, // Repulsion between nodes, negative value for repulsionedgeStrength: 0.5, // Edge strength, affects edge length});
Example 2: Update layout using a function
// Update based on the current layout configurationgraph.setLayout((prevLayout) => {// If the previous layout was force-directed, adjust its parametersif (prevLayout.type === 'force') {return {...prevLayout,preventOverlap: true,nodeStrength: -100, // Increase repulsionalphaDecay: 0.01, // Lower decay rate for more iteration time};}// Otherwise, switch to radial layoutreturn {type: 'radial',unitRadius: 100,preventOverlap: true,};});
Example 3: Set a combined layout
// Set a combined layout - different nodes use different layout algorithmsgraph.setLayout([{type: 'grid',// Filter function: only nodes with type 'main' participate in the layoutnodeFilter: (node) => node.data.type === 'main',rows: 1,},{type: 'circle',nodeFilter: (node) => node.data.type === 'sub',radius: 100,},]);
Get the current layout configuration.
getLayout(): LayoutOptions;
Return Value
Example
// Get the current layout configurationconst currentLayout = graph.getLayout();console.log('Current layout type:', currentLayout.type);
Execute layout calculations. When graph data changes, call this method to trigger the layout algorithm to recalculate node positions.
layout(layoutOptions?: LayoutOptions): Promise<void>;
Parameters
Parameter | Description | Type | Default | Required |
---|---|---|---|---|
layoutOptions | Layout configuration object | LayoutOptions | ((prev: LayoutOptions) => LayoutOptions) | - |
If layoutOptions
is provided, it takes precedence over the graph's current layout configuration.
Note
Layout calculation is an asynchronous process, especially for complex layout algorithms like force-directed layout. This method returns a Promise, which can be used to perform subsequent operations after the layout is complete.
Example 1: Basic usage
// Execute layoutawait graph.layout();console.log('Layout calculation complete');
Example 2: Re-layout after adding data
// Add new nodes and edgesgraph.addData({nodes: [{ id: 'newNode1' }, { id: 'newNode2' }],edges: [{ id: 'newEdge', source: 'existingNode', target: 'newNode1' }],});// Draw new nodes and edgesawait graph.draw();// Recalculate layoutawait graph.layout();
Example 3: Listen to layout events
import { GraphEvent } from '@antv/g6';// Before layout startsgraph.on(GraphEvent.BEFORE_LAYOUT, () => {console.log('Layout calculation starting...');});// After layout completesgraph.on(GraphEvent.AFTER_LAYOUT, () => {console.log('Layout calculation complete');});// Execute layoutgraph.layout();
Stop an ongoing layout calculation. Mainly used to stop iterative layout algorithms like force-directed layout.
stopLayout(): void;
Note
Applicable to layouts with iterative animations, currently force
belongs to this category. If the layout calculation takes too long, you can manually stop the iteration.
Example 1: Basic usage
// Stop layout after 5 secondssetTimeout(() => {graph.stopLayout();console.log('Layout manually stopped');}, 5000);
Example 2: Stop layout with user interaction
// Stop layout when the user clicks the canvasimport { CanvasEvent } from '@antv/g6';graph.on(CanvasEvent.CLICK, () => {graph.stopLayout();console.log('User clicked canvas, layout stopped');});
Layout configuration type, can be a single layout configuration or an array of layout configurations.
type LayoutOptions = SingleLayoutOptions | SingleLayoutOptions[];
Single layout configuration, can be a built-in layout configuration or a custom base layout configuration.
type SingleLayoutOptions = BuiltInLayoutOptions | BaseLayoutOptions;
Basic configuration items common to all layout types.
interface BaseLayoutOptions {// Layout typetype: string;// Node filter function for participating in the layoutnodeFilter?: (node: NodeData) => boolean;// Whether to calculate the layout before initializing elementspreLayout?: boolean;// Whether invisible nodes participate in the layout (effective when preLayout is true)isLayoutInvisibleNodes?: boolean;// Enable layout animation, for iterative layouts, animation transitions occur between iterationsanimation?: boolean;// Whether to run the layout in a WebWorkerenableWorker?: boolean;// Number of iterations for iterative layoutsiterations?: number;// Other specific layout configuration items[key: string]: any;}
Configuration for G6's built-in layout types, see API - Built-in Layouts for details.