力布局+调整
默认布局是物理模拟:节点相互排斥,链接像弹簧一样,温和的重力使所有东西都居中。三个旋钮塑造了结果——将它们从紧密的结调整为通风、可读的地图。
d3ManyBodyStrength(默认-150) — 硬节点推开的程度。负数越多,图表就越分散。d3LinkDistance(默认30) — 每个链接的静止长度。d3GravityStrengthConnected(默认0.001) — 链接节点上的居中拉力。较高的采集图;接近于零的默认值让链接和排斥力来解决它。 (孤独的无边节点使用d3GravityStrength,默认0.1,因此它们不会自行漂移。)
拖动一个节点,模拟会在其周围重新设置。
js
const options = {
layout: { type: 'force' },
simulation: {
// Repulsion between every pair of nodes (negative = push apart).
// Default -150. A stronger push spreads the graph out and untangles
// dense clusters — raise it when nodes overlap.
d3ManyBodyStrength: -360,
// Resting length of each link. Default 30. Longer links give connected
// nodes more breathing room.
d3LinkDistance: 70,
// Centering pull for connected nodes (the ones with edges). Defaults to a
// tiny 0.001 so links + repulsion find their own balance; raise it to gather
// the graph toward the middle instead of letting it sprawl. Lower = looser
// and airier; higher = a tighter ball.
d3GravityStrengthConnected: 0.05,
// The pull for isolated, edge-less nodes (default 0.1) is a separate knob —
// d3GravityStrength — so a lone node still can't drift off on its own.
d3GravityStrength: 0.1
}
}js
const data = {
nodes: [
{ id: 'core' },
{ id: 'api' },
{ id: 'web' },
{ id: 'mobile' },
{ id: 'auth' },
{ id: 'billing' },
{ id: 'search' },
{ id: 'index' },
{ id: 'queue' },
{ id: 'worker' },
{ id: 'db' },
{ id: 'cache' },
{ id: 'cdn' },
{ id: 'logs' }
],
edges: [
{ from: 'web', to: 'api' },
{ from: 'mobile', to: 'api' },
{ from: 'api', to: 'core' },
{ from: 'api', to: 'auth' },
{ from: 'api', to: 'billing' },
{ from: 'api', to: 'search' },
{ from: 'search', to: 'index' },
{ from: 'core', to: 'queue' },
{ from: 'queue', to: 'worker' },
{ from: 'worker', to: 'db' },
{ from: 'core', to: 'db' },
{ from: 'api', to: 'cache' },
{ from: 'web', to: 'cdn' },
{ from: 'worker', to: 'logs' },
{ from: 'auth', to: 'db' },
{ from: 'billing', to: 'db' }
]
}