基础概念: 力导向图(Force-directed graph)是一种图形布局算法,它模拟了物理系统中的力来排列图中的节点。在这种布局中,节点被视为带有电荷的粒子,而边则类似于弹簧。节点之间的斥力和边上的引力共同作用,使得整个图形达到一种平衡状态。
优势:
类型:
应用场景:
常见问题及解决方法:
示例代码(使用jQuery和D3.js实现力导向图):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Force-directed Graph Example</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="graph"></div>
<script>
const width = 800;
const height = 600;
const svg = d3.select("#graph")
.append("svg")
.attr("width", width)
.attr("height", height);
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
const graph = {
nodes: [
{id: "A"},
{id: "B"},
{id: "C"},
// ... more nodes
],
links: [
{source: "A", target: "B"},
{source: "B", target: "C"},
// ... more links
]
};
const link = svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", d => Math.sqrt(d.value));
const node = svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 10)
.call(d3.drag()
.on("start", dragStarted)
.on("drag", dragged)
.on("end", dragEnded));
node.append("title")
.text(d => d.id);
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
link
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
node
.attr("cx", d => d.x)
.attr("cy", d => d.y);
}
function dragStarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragEnded(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
</script>
</body>
</html>
这段代码创建了一个简单的力导向图,其中包含了节点和边的定义,以及拖拽交互功能。
领取专属 10元无门槛券
手把手带您无忧上云