logo

G6

  • Docs
  • API
  • Playground
  • Community
  • Productsantv logo arrow
  • 5.0.49
  • Introduction
  • Data
  • Getting Started
    • Quick Start
    • Installation
    • Integration
      • react
      • vue
      • angular
    • Step-by-step guide
  • Graph
    • Extensions En
    • Graph
    • Options
    • extension
  • Element
    • Element Overview
    • Element State
    • Node
      • Node Overview
      • Build-in Node
        • Common Node Configurations
        • Diamond
        • Donut
        • Ellipse
        • Hexagon
        • Html
        • Image
        • Rect
        • Star
        • Triangle
        • Circle
      • Custom Node
      • Define Nodes with React
    • Edge
      • Edge Overview
      • Build-in Edge
        • Common Edge Configurations
        • Cubic Bezier Curve
        • CubicHorizontal Bezier Curve
        • CubicVertical Bezier Curve
        • Line
        • Polyline
        • Quadratic Bezier Curve
      • Custom Edge
    • Combo
      • Combo Overview
      • Build-in Combo
        • Circle
        • Combo Configuration Options
        • Rect
      • Custom Combo
    • Shape
      • Shape and KeyShape
      • Atomic Shapes and Their Properties
      • Design and Implementation of Composite Shape
  • Layout
    • Layout Overview
    • Build-in Layout
      • 3D Force-Directed Layout
      • AntvDagre Layout
      • Circular Layout
      • ComboCombined Layout
      • Common Layout Configuration Options
      • CompactBox
      • Concentric Layout
      • D3 Force-Directed Layout
      • Dagre Layout
      • Dendrogram Layout
      • Fishbone Layout
      • Force-directed Layout
      • ForceAtlas2 Force-directed Layout
      • Fruchterman Force-directed Layout
      • Grid Layout
      • Indented Tree
      • MDS High-dimensional Data Dimensionality Reduction Layout
      • Mindmap Tree
      • Radial Layout
      • Random Layout
      • Snake Layout
    • Custom Layout
  • Behavior
    • Behavior Overview
    • Build-in Behavior
      • AutoAdaptLabel
      • BrushSelect
      • ClickSelect
      • CollapseExpand
      • CreateEdge
      • DragCanvas
      • DragElement
      • DragElementForce
      • FixElementSize
      • FocusElement
      • HoverActivate
      • LassoSelect
      • OptimizeViewportTransform
      • ScrollCanvas
      • ZoomCanvas
    • Custom Behavior
  • Plugin
    • Plugin Overview
    • Build-in Plugin
      • Background
      • BubbleSets
      • Contextmenu
      • EdgeBundling
      • EdgeFilterLens
      • Fisheye
      • Fullscreen
      • GridLine
      • History
      • Hull
      • Legend
      • Minimap
      • Snapline
      • Timebar
      • Toolbar
      • Tooltip
      • Watermark
    • Custom Plugin
  • Transform
    • Data Transformation Overview
    • Build-in Transform
      • MapNodeSize
      • PlaceRadialLabels
      • ProcessParallelEdges
    • Custom Transform
  • Theme
    • Theme Overview
    • Custom Theme
    • Palette
    • Custom Palette
  • Animation
    • Animation Overview
    • Custom Animation
  • Further Reading
    • Event
    • renderer
    • coordinate
    • download-image
    • Using Iconfont
    • Use 3D
    • Bundle Project
  • What's new
    • Feature
    • Upgrade To 5.0
  • FAQ
  • contribute

Force-directed Layout

Previous
Fishbone Layout
Next
ForceAtlas2 Force-directed Layout

Resource

Ant Design
Galacea Effects
Umi-React Application Framework
Dumi-Component doc generator
ahooks-React Hooks Library

Community

Ant Financial Experience Tech
seeconfSEE Conf-Experience Tech Conference

Help

GitHub
StackOverflow

more productsMore Productions

Ant DesignAnt Design-Enterprise UI design language
yuqueYuque-Knowledge creation and Sharing tool
EggEgg-Enterprise-class Node development framework
kitchenKitchen-Sketch Tool set
GalaceanGalacean-Interactive solution
xtechLiven Experience technology
© Copyright 2025 Ant Group Co., Ltd..备案号:京ICP备15032932号-38

Loading...

Overview

Force-directed layout is a graph layout algorithm based on physical simulation that determines node positions by simulating attraction and repulsion forces between nodes. This layout is particularly suitable for displaying complex relationship networks, such as social networks and knowledge graphs.

The force-directed layout automatically calculates and adjusts node positions to maintain appropriate distances between connected nodes while minimizing edge crossings. During the layout process, it simulates a physical system where nodes repel each other like charged particles, and edges connect nodes like springs.

Key features of force-directed layout include:

  1. Automatic Arrangement: No need to manually set node positions, the system automatically finds suitable positions
  2. Real-time Adjustment: When you drag a node, other nodes will adjust their positions in real-time
  3. Flexible Configuration:
    • Can adjust attraction and repulsion forces between nodes
    • Can set edge lengths
    • Can prevent node overlap
  4. Animation Effects: Smooth animations during node movement make changes more natural
Force-directed Layout Example

Core Concepts

Basic Principles of Force-directed Layout

Force-directed layout is a graph layout algorithm based on physical simulation that models nodes and edges as a physical system:

  • Nodes are treated as physical particles
  • Edges are treated as springs
  • The entire system reaches its lowest energy state through physical simulation

Detailed Core Forces

Node Repulsion

  • Physical Model: Coulomb's Law

  • Function: Prevents node overlap and ensures more uniform node distribution, where factor and coulombDisScale control the overall strength and range of repulsion.

  • Formula: Repulsion Force

    • k: Repulsion coefficient (factor / coulombDisScale²)
    • q1,q2: Node strength (nodeStrength)
    • r: Distance between nodes

Edge Attraction

  • Physical Model: Hooke's Law

  • Function: Simulates edge tension, moving nodes along edge directions, where edgeStrength and linkDistance control edge "stiffness" and length.

  • Formula: Edge Attraction

    • ka: Edge attraction strength (edgeStrength)
    • L: Edge length (linkDistance)
    • r: Actual edge length

Centripetal Force

  • Physical Model: Newton's Universal Law of Gravitation

  • Function: Attracts nodes toward the canvas center or cluster centers, where gravity and center control gravity strength and center point position

  • Formula: Centripetal Force

    • G: Gravitational constant (gravity)
    • xc: Center point coordinates (center)
    • mass: Node mass (nodeSize)

Interaction of Three Forces

  • Physical Model: Force interactions, generating acceleration
  • Function: Repulsion, edge attraction, and centripetal force work together, affecting node movement through acceleration superposition, ultimately reaching the lowest energy state.
  • Formula: Force Interactions

Physical System

Node Velocity Formula

  • Formula: Node Velocity Formula

    • v: Velocity
    • a: Acceleration
    • dt: Time step (interval)
    • damping: Damping coefficient (damping)
  • Function:

    1. Controls node movement stability
    2. Damping coefficient prevents system oscillation
    3. Time step affects displacement per iteration

Node Position Formula

  • Formula: Node Position Formula

    • x: Node position
    • v: Node velocity
    • dt: Time step (interval)
  • Function:

    1. Updates node position based on velocity
    2. Ensures motion continuity
    3. Prevents node overlap through preventOverlap

Cluster Center Calculation

  • Formula: Cluster Center Calculation

    • n: Number of nodes in cluster
    • (xi​,yi​): Position of each node
  • Function:

    1. Calculates cluster center
    2. Centripetal force pulls nodes toward their cluster center
    3. Cluster center can change dynamically

Cluster Strength Calculation

  • Formula: Cluster Strength Calculation

    • s: Cluster strength (clusterNodeStrength)
    • xc​: Cluster center
  • Function:

    1. Controls cluster compactness
    2. Higher cluster strength means tighter clusters
    3. Can be dynamically adjusted based on node properties

Mass Effect on Forces

  • Formula: Mass Effect on Forces

    • a: Acceleration
    • F: Force (repulsion, edge attraction, centripetal force)
    • mass: Node mass
  • Function:

    1. Nodes with larger mass move less
    2. Nodes with smaller mass move more
    3. Mass calculation can be customized through getMass

Energy Calculation

  • Formula: Energy Calculation

    • m: Node mass
    • v: Node velocity
  • Function:

    1. Monitors layout convergence
    2. System stabilizes when energy approaches zero

System Convergence Condition

  • Formula: System Convergence Condition

  • Function:

    1. Controls iteration count
    2. Stops when movement is below threshold
    3. Can choose between mean, maximum, or minimum through distanceThresholdMode

Force Interaction Diagram

graph TD
A[Input] --> B[Initialize Parameters];
B --> C[Build Layout Calculation];
C --> D[Iterative Calculation];
D --> E{Converged?};
E -->|Yes| F[Output Layout];
E -->|No| G[Calculate Repulsion];
G --> H[Calculate Edge Attraction];
H --> I[Calculate Centripetal Force];
I --> J[Update Velocity];
J --> K[Update Position];
K --> D;
Force Simulation Diagram

Configuration Options

Based on the physical characteristics of force-directed layout, the following configuration options are available:

Basic Configuration

PropertyDescriptionDefault ValueRequired
typeLayout typeforce✓
dimensionsLayout dimensions, 2 for 2D layout, 3 for 3D layout2
widthLayout widthCanvas width
heightLayout heightCanvas height
centerLayout center pointGraph center
maxIterationMaximum iteration count, if 0 will auto-adjust0
minMovementStop iteration when average movement distance is less than 0.40.4
distanceThresholdModeMovement distance calculation mode: mean: stop when average movement distance is less than minMovement; max: stop when maximum movement distance is less than minMovement; min: stop when minimum movement distance is less than minMovementmean
maxDistanceMaximum distance

Force-related Configuration

Repulsion Configuration

PropertyDescriptionDefault ValueRequired
nodeStrengthNode force, positive values represent attraction between nodes, negative values represent repulsion1000
factorRepulsion coefficient, larger values mean stronger repulsion1
coulombDisScaleCoulomb coefficient, a factor for repulsion, larger values mean stronger repulsion between nodes0.005

Edge Attraction Configuration

PropertyDescriptionDefault ValueRequired
edgeStrengthEdge force (attraction) strength, fixed force or callback function to dynamically return different edge forces500
linkDistanceEdge length, fixed length or callback function to dynamically return different edge lengths200

Centripetal Force Configuration

PropertyDescriptionDefault ValueRequired
gravityCenter force strength, the force attracting all nodes to the center. Larger values mean more compact layout10
centripetalOptionsCentripetal force configuration, including center and strength for leaf nodes, isolated nodes, and other nodes. leaf: leaf node centripetal force; single: single node centripetal force; others: other node centripetal force; center: custom center point function[0, 0]

Clustering Configuration

PropertyDescriptionDefault ValueRequired
clusteringWhether to cluster all nodes. If true, will use the field specified by nodeClusterBy in node data for clustering. centripetalOptions.single, centripetalOptions.leaf, and centripetalOptions.others will use the value returned by getClusterNodeStrength; leaf and centripetalOptions.center will use the average center of all nodes in the current clusterfalse
nodeClusterBySpecifies the field name in node data for clustering. Takes effect when clustering is true. Automatically generates centripetalOptions, can be used with clusterNodeStrength
clusterNodeStrengthUsed with clustering and nodeClusterBy to specify the strength of the cluster centripetal force
leafClusterWhether to cluster leaf nodes. If true, centripetalOptions.single will be 100; centripetalOptions.leaf will use the value returned by getClusterNodeStrength; getClusterNodeStrength.center will return the average center of all leaf nodesfalse

Performance and Optimization Configuration

PropertyDescriptionDefault ValueRequired
dampingDamping coefficient, range [0, 1]. Larger values mean slower speed decrease0.9
maxSpeedMaximum movement length per iteration200
intervalControls the movement speed of each node per iteration0.02
preventOverlapWhether to prevent overlap. Must be used with nodeSize or data.size in node data. Only when data.size is set in the data or nodeSize is configured in the layout with the same value as the node size in the graph, collision detection for node overlap can be performedtrue
nodeSizeNode size (diameter). Used for collision detection to prevent node overlap. Fixed size or callback function to dynamically return node size
nodeSpacingTakes effect when preventOverlap is true. Minimum spacing between node edges to prevent overlap. Can be a callback to set different spacing for different nodes
collideStrengthStrength of anti-overlap force, range [0, 1]1

Other Configuration

PropertyDescriptionDefault ValueRequired
getMassCallback for the mass of each node. The parameter is the node's internal data, and the return value is the mass
getCenterCallback for the x, y, and strength of the centripetal force for each node. If not specified, no extra centripetal force is applied
onTickCallback for each iteration
monitorCallback for monitoring each iteration. energy indicates the convergence energy of the layout. May incur extra computation if configured; if not configured, no computation is performed

Code Examples

Basic Usage

const graph = new Graph({
container: 'container',
layout: {
type: 'force',
// Prevent node overlap
preventOverlap: true,
// Node size
nodeSize: 20,
// Layout width
width: 800,
// Layout height
height: 600,
},
});

Preventing Node Overlap

const graph = new Graph({
layout: {
type: 'force',
// Prevent node overlap
preventOverlap: true,
// Node size
nodeSize: 20,
},
});

Force-directed Layout

This example demonstrates how to create a basic force-directed graph using force-directed layout.

import { Graph, NodeEvent } from '@antv/g6';
const data = {
nodes: [
{ id: 'node1', label: 'Node 1', size: 30 },
{ id: 'node2', label: 'Node 2', size: 20 },
{ id: 'node3', label: 'Node 3', size: 20 },
{ id: 'node4', label: 'Node 4', size: 20 },
{ id: 'node5', label: 'Node 5', size: 30 },
{ id: 'node6', label: 'Node 6', size: 20 },
],
edges: [
{ source: 'node1', target: 'node2' },
{ source: 'node1', target: 'node3' },
{ source: 'node2', target: 'node4' },
{ source: 'node3', target: 'node4' },
{ source: 'node4', target: 'node5' },
{ source: 'node5', target: 'node6' },
],
};
const graph = new Graph({
container: 'container',
data,
autoFit: 'view',
modes: {
default: ['drag-canvas', 'zoom-canvas'],
},
layout: {
type: 'force',
// Prevent node overlap
preventOverlap: true,
// Node size
nodeSize: 20,
// Centripetal force
gravity: 0.9,
// Iteration count
iterations: 100,
},
node: {
style: {
size: (d) => d.size,
fill: '#9EC9FF',
stroke: '#69C8FF',
label: (d) => d.label,
labelPlacement: 'center',
labelFill: '#333',
},
},
edge: {
style: {
stroke: '#e2e2e2',
},
},
});
graph.on(NodeEvent.CLICK, async (e) => {
const nodeId = e.target.id;
graph.updateNodeData([{ id: nodeId, size: 200 }]);
await graph.render();
});
graph.render();

Key configuration explanations:

  • preventOverlap: Enable node overlap detection
  • nodeSize: Set node size
  • gravity: Set node centripetal force
  • iterations: Set layout calculation precision

You can also refer to View Examples for more usage examples.