Skip to main content

Overview

The ForceDirected class creates a force-directed network diagram where nodes are positioned using physics-based simulation. Nodes attract or repel each other based on configured forces.
import * as am5hierarchy from "@amcharts/amcharts5/hierarchy";

const forceDirected = root.container.children.push(
  am5hierarchy.ForceDirected.new(root, {
    centerStrength: 0.5,
    manyBodyStrength: -15
  })
);

Class Hierarchy

  • Series
    • Hierarchy
      • LinkedHierarchy
        • ForceDirected

Settings

nodePadding

nodePadding
number
Minimum gap in pixels between the nodes.
forceDirected.set("nodePadding", 10);

centerStrength

centerStrength
number
default:"0.5"
A force that attracts (or pushes back) all nodes to the center of the chart.
  • Positive values attract nodes to center
  • Negative values push nodes away from center
  • Higher absolute values = stronger force
forceDirected.set("centerStrength", 1.2);

manyBodyStrength

manyBodyStrength
number
default:"-15"
A force that attracts (or pushes back) all nodes to each other.
  • Negative values make nodes repel each other (typical)
  • Positive values make nodes attract each other
  • Higher absolute values = stronger force
forceDirected.set("manyBodyStrength", -20);

linkWithStrength

A force that attracts (or pushes back) nodes that are linked together via linkWithField.Controls the strength of custom links between non-hierarchical nodes.
forceDirected.set("linkWithStrength", 0.8);

velocityDecay

velocityDecay
number
default:"0.5"
Resistance acting against node speed.The greater the value, the more “sluggish” the nodes will be.
  • Range: 0 to 1
  • Higher values = more friction/slower movement
forceDirected.set("velocityDecay", 0.7);

initialFrames

initialFrames
number
default:"500"
Length of how long initial force simulation would run in frames.The simulation runs for this many frames to settle nodes into position before displaying.
forceDirected.set("initialFrames", 300);

showOnFrame

showOnFrame
number
default:"10"
If set to a number, will wait X number of frames before revealing the tree.Can be used to hide initial animations where nodes settle into their places.
forceDirected.set("showOnFrame", 50);

minRadius

minRadius
number | Percent
default:"1%"
Smallest possible radius for a node circle.Can be a fixed pixel value or percent relative to chart size.
forceDirected.set("minRadius", am5.percent(2));
forceDirected.set("minRadius", 15); // 15 pixels

maxRadius

maxRadius
number | Percent
default:"8%"
Biggest possible radius for a node circle.Can be a fixed pixel value or percent relative to chart size.
forceDirected.set("maxRadius", am5.percent(10));
forceDirected.set("maxRadius", 50); // 50 pixels

xField

xField
string
Field in data that holds X coordinate of the node.Use to position specific nodes at fixed locations.
forceDirected.set("xField", "x");

yField

yField
string
Field in data that holds Y coordinate of the node.Use to position specific nodes at fixed locations.
forceDirected.set("yField", "y");

Inherited Settings

ForceDirected inherits all settings from LinkedHierarchy and Hierarchy, including:
  • sort - How to sort nodes by value (“ascending” | “descending” | “none”)
  • valueField - Field in data holding numeric value
  • categoryField - Field in data holding category name
  • childDataField - Field in data holding array of children
  • downDepth - Number of child levels to show when drilling down
  • upDepth - Number of parent levels to show from selected node
  • initialDepth - Number of levels to show on first load
  • topDepth - Starting level to show (hides upper levels)
  • singleBranchOnly - Collapse other branches when one expands
  • animationDuration - Duration for drill animations in milliseconds
  • animationEasing - Easing function for animations
  • colors - ColorSet for auto-assigning node colors
  • patterns - PatternSet for auto-assigning node patterns
  • linkWithField - Field holding IDs of nodes to link with

Data Item Properties

Each data item in a ForceDirected chart has the following properties:

children

children
Array<DataItem<IForceDirectedDataItem>>
An array of data items of child nodes.

parent

parent
DataItem<IForceDirectedDataItem>
Data item of a parent node.

x

x
number | undefined
X coordinate for fixed positioning.When set, the node will be locked to this position.

y

y
number | undefined
Y coordinate for fixed positioning.When set, the node will be locked to this position.

value

value
number
Value of the node as set in data.

sum

sum
number
Sum of child values.

valuePercentTotal

valuePercentTotal
number
Percent value of the node, based on total sum of all nodes in upper level.

valuePercent

valuePercent
number
Percent value of the node, based on the value of its direct parent.Since: 5.2.21

category

category
string
Category name of the node.

depth

depth
number
Node’s depth within the hierarchy (0 for root).

node

node
LinkedHierarchyNode
Reference to the visual LinkedHierarchyNode element.

circle

circle
Circle
Circle element of the node.

outerCircle

outerCircle
Circle
Outer circle element of the node (shown for nodes with children).

label

label
Label
Reference to node’s Label element.

fill

fill
Color
Node’s auto-assigned color.

fillPattern

fillPattern
Pattern
Node’s auto-assigned pattern.Since: 5.10.0

disabled

disabled
boolean
Indicates if node is currently disabled (collapsed).
HierarchyLink leading to parent node.
Array of HierarchyLink objects leading to child nodes.

linkWith

Array of IDs of directly linked nodes (for custom cross-links).

Data Format

interface IForceDirectedDataObject {
  name?: string;
  value?: number;
  children?: IForceDirectedDataObject[];
}

Example Data

forceDirected.data.setAll([{
  name: "Central Node",
  value: 0,
  children: [
    {
      name: "Branch 1",
      value: 10,
      children: [
        { name: "Leaf 1.1", value: 5 },
        { name: "Leaf 1.2", value: 3 }
      ]
    },
    {
      name: "Branch 2",
      value: 15,
      children: [
        { name: "Leaf 2.1", value: 8 },
        { name: "Leaf 2.2", value: 7 }
      ]
    }
  ]
}]);

Example with Fixed Positions

forceDirected.data.setAll([{
  name: "Center",
  value: 10,
  x: 400,  // Fixed X position
  y: 300,  // Fixed Y position
  children: [
    { name: "Node 1", value: 5 },
    { name: "Node 2", value: 8 }
  ]
}]);

List Templates

ForceDirected provides access to these list templates for customization:

nodes

nodes
ListTemplate<LinkedHierarchyNode>
List of all node elements.
forceDirected.nodes.template.setAll({
  toggleKey: "disabled",
  draggable: true
});

circles

circles
ListTemplate<Circle>
List of node circle elements.
forceDirected.circles.template.setAll({
  strokeWidth: 2,
  fillOpacity: 0.8
});

outerCircles

outerCircles
ListTemplate<Circle>
List of node outer circle elements (shown for nodes with children).
forceDirected.outerCircles.template.setAll({
  strokeWidth: 2,
  strokeOpacity: 0.3
});

labels

labels
ListTemplate<Label>
List of label elements.
forceDirected.labels.template.setAll({
  text: "{category}",
  fontSize: 11,
  centerX: am5.p50,
  centerY: am5.p50
});
List of link elements connecting nodes.
forceDirected.links.template.setAll({
  strokeWidth: 1,
  strokeOpacity: 0.5,
  distance: 1.5
});

Containers

nodesContainer

nodesContainer
Container
Container that holds all node elements.
Container that holds all link elements.

Public Properties

d3forceSimulation

d3forceSimulation
d3Force.Simulation
The underlying D3 force simulation instance.Advanced users can access this to customize simulation parameters directly.

collisionForce

collisionForce
d3Force.ForceCollide
The collision force that prevents nodes from overlapping.

linkForce

The force that connects linked nodes.

Methods

restartSimulation()

restartSimulation(alpha: number): void
Restarts the force simulation with the given alpha (energy) value.
alpha
number
Energy level for the simulation (0 to 1).
forceDirected.restartSimulation(0.5);

updateNodePositions()

updateNodePositions(): void
Updates visual node positions based on the force simulation state. Called automatically on each simulation tick.

updateLinkWith()

updateLinkWith(dataItems: Array<DataItem<IForceDirectedDataItem>>): void
Updates custom links between nodes based on linkWith data.
dataItems
Array<DataItem<IForceDirectedDataItem>>
Array of data items to process.

selectDataItem()

selectDataItem(dataItem: DataItem<IForceDirectedDataItem>): void
Selects a specific data item.
dataItem
DataItem<IForceDirectedDataItem>
The data item to select.

getDataItemById()

getDataItemById(id: string): DataItem<IForceDirectedDataItem> | undefined
Looks up and returns a data item by its ID.
id
string
The ID to search for.
return
DataItem<IForceDirectedDataItem> | undefined
The found data item, or undefined if not found.

linkDataItems()

linkDataItems(
  source: DataItem<IForceDirectedDataItem>,
  target: DataItem<IForceDirectedDataItem>,
  strength?: number
): HierarchyLink
Creates a link between two data items.
source
DataItem<IForceDirectedDataItem>
Source node data item.
target
DataItem<IForceDirectedDataItem>
Target node data item.
strength
number
Optional link strength.
return
HierarchyLink
The created or existing link element.

unlinkDataItems()

unlinkDataItems(
  source: DataItem<IForceDirectedDataItem>,
  target: DataItem<IForceDirectedDataItem>
): void
Removes a link between two data items.
source
DataItem<IForceDirectedDataItem>
Source node data item.
target
DataItem<IForceDirectedDataItem>
Target node data item.

areLinked()

areLinked(
  source: DataItem<IForceDirectedDataItem>,
  target: DataItem<IForceDirectedDataItem>
): boolean
Returns true if two nodes are linked with each other.
source
DataItem<IForceDirectedDataItem>
Source node data item.
target
DataItem<IForceDirectedDataItem>
Target node data item.
return
boolean
True if nodes are linked, false otherwise.

enableDataItem()

enableDataItem(
  dataItem: DataItem<IForceDirectedDataItem>,
  maxDepth?: number,
  depth?: number,
  duration?: number
): void
Enables a disabled (collapsed) data item.
dataItem
DataItem<IForceDirectedDataItem>
Target data item to enable.
maxDepth
number
Maximum depth to enable children to.
depth
number
Current depth (used internally for recursion).
duration
number
Animation duration in milliseconds.

disableDataItem()

disableDataItem(
  dataItem: DataItem<IForceDirectedDataItem>,
  duration?: number
): void
Disables (collapses) a data item.
dataItem
DataItem<IForceDirectedDataItem>
Target data item to disable.
duration
number
Animation duration in milliseconds.

addChildData()

addChildData(
  dataItem: DataItem<IForceDirectedDataItem>,
  data: Array<any>
): void
Adds children data to the target data item dynamically.
dataItem
DataItem<IForceDirectedDataItem>
Parent data item to add children to.
data
Array<any>
Array of child data objects.
Since: 5.4.5

hoverDataItem()

hoverDataItem(dataItem: DataItem<IForceDirectedDataItem>): void
Triggers hover state on a data item.
dataItem
DataItem<IForceDirectedDataItem>
Target data item.
Since: 5.0.7

unhoverDataItem()

unhoverDataItem(dataItem: DataItem<IForceDirectedDataItem>): void
Removes hover state from a data item.
dataItem
DataItem<IForceDirectedDataItem>
Target data item.
Since: 5.0.7

Events

dataitemselected

forceDirected.events.on("dataitemselected", (ev) => {
  console.log("Selected:", ev.dataItem);
});
Fired when a data item is selected.
dataItem
DataItem<IForceDirectedDataItem> | undefined
The selected data item.

See Also

Build docs developers (and LLMs) love