力导向图(Force-Directed Graph)是一种用于表示网络结构的可视化图表,其中节点(代表实体)通过边(代表关系)相互连接。力导向图的布局算法模拟了物理系统中的力,使得节点在受到边和其他节点的“力”作用后,达到一个相对平衡的状态。
以下是一个简单的力导向图示例,使用D3.js库:
<!DOCTYPE html>
<html>
<head>
<title>Force-Directed Graph</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<svg width="600" height="400"></svg>
<script>
const width = 600, height = 400;
const svg = d3.select("svg");
const nodes = [
{id: "A"}, {id: "B"}, {id: "C"}, {id: "D"}, {id: "E"}
];
const links = [
{source: "A", target: "B"},
{source: "A", target: "C"},
{source: "B", target: "C"},
{source: "C", target: "D"},
{source: "D", target: "E"}
];
const simulation = d3.forceSimulation(nodes)
.force("link", d3.forceLink(links).id(d => d.id))
.force("charge", d3.forceManyBody().strength(-400))
.force("center", d3.forceCenter(width / 2, height / 2));
const link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(links)
.enter().append("line")
.attr("stroke-width", 2);
const node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", 10)
.call(drag(simulation));
simulation.on("tick", () => {
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 drag(simulation) {
function dragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}
function dragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}
function dragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
</script>
</body>
</html>
这个示例展示了如何使用D3.js创建一个简单的力导向图,并处理节点的拖动事件。通过调整力导向图的参数,可以优化图表的布局和性能。
没有搜到相关的文章