一、基础概念
二、优势
三、类型
四、应用场景
五、可能遇到的问题及解决方法
以下是一个简单的d3.js绘制人物关系图(力导向图)的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
<meta name="viewport" content="width=device-width, initial - scale = 1.0">
<title>D3.js人物关系图示例</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
.node {
stroke: #fff;
stroke - width: 1.5px;
}
.link {
stroke: #999;
stroke - opacity: 0.6;
}
</style>
</head>
<body>
<script>
// 数据示例,人物及其关系
const data = {
"nodes": [
{ "id": "Alice" },
{ "id": "Bob" },
{ "id": "Charlie" },
{ "id": "David" }
],
"links": [
{ "source": "Alice", "target": "Bob" },
{ "source": "Bob", "target": "Charlie" },
{ "source": "Charlie", "target": "David" },
{ "source": "Alice", "target": "David" }
]
};
const width = 800;
const height = 600;
const svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
const simulation = d3.forceSimulation(data.nodes)
.force("link", d3.forceLink(data.links).id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
const link = svg.append("g")
.attr("class", "link")
.selectAll("line")
.data(data.links)
.enter().append("line");
const node = svg.append("g")
.attr("class", "node")
.selectAll("circle")
.data(data.nodes)
.enter().append("circle")
.attr("r", 10);
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);
});
</script>
</body>
</html>
这个示例创建了一个简单的人物关系图,包含4个节点和4条边,通过d3.js的力导向图模拟来布局节点位置。