图可视化是一种将复杂的数据关系通过图形化的方式展示出来的技术,它可以帮助用户更直观地理解和分析数据之间的关联。年末活动使用图可视化可以增强活动的互动性和教育性,同时也能够提升数据的呈现效果。
图可视化主要涉及图论的基本概念,包括节点(Node)、边(Edge)和图(Graph)。节点代表实体,边表示实体之间的关系,图则是这些节点和边的集合。
// 创建SVG容器
const svg = d3.select("body").append("svg")
.attr("width", 800)
.attr("height", 600);
// 定义力导向图布局
const simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(400, 300));
// 加载数据并渲染图
d3.json("data.json").then(data => {
const link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(data.links)
.enter().append("line")
.attr("stroke-width", 2);
const node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(data.nodes)
.enter().append("circle")
.attr("r", 5)
.call(d3.drag()
.on("start", dragStarted)
.on("drag", dragged)
.on("end", dragEnded));
node.append("title")
.text(d => d.id);
simulation
.nodes(data.nodes)
.on("tick", ticked);
simulation.force("link")
.links(data.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;
}
在这个示例中,我们使用了D3.js库来创建一个简单的力导向图。通过加载JSON数据,我们可以渲染节点和边,并允许用户通过拖拽来互动。