我正在尝试使用this force-directed graph。现在我能够很好地编写图表,但由于我的图表有2000个节点,因此感觉非常迟钝。所以我决定删除起始动画但仍无法找到方法。我已经看过Static Force Layout并尝试解决但仍然无效。
有没有办法删除动画或有其他方法来减少延迟?
这是我的代码:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.links line {
stroke: #999;
stroke-opacity: 0.6;
}
.nodes circle {
stroke: #fff;
stroke-width: 1.5px;
}
</style>
<svg width="2000" height="1500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var color = d3.scaleOrdinal(d3.schemeCategory20);
var simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function(d) { return d.id; }))
.force("center", d3.forceCenter(width / 2, height / 2));
d3.json("force.json", function(error, graph) {
if (error) throw error;
// Taken from related answer: https://stackoverflow.com/a/44113223/4235784
let filteredNodes = graph.nodes.filter(
function(n) { return this.has(n.id); },
graph.links.reduce((set, {source:s, target:t}) =>
s !== t ? set.add(s).add(t) : set,
new Set()
)
);
var link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(graph.links)
.enter().append("line")
.attr("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(filteredNodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", function(d) { return color(d.group); });
node.append("title")
.text(function(d) { return d.name; });
simulation
.nodes(graph.nodes)
.on("tick", ticked);
simulation.force("link")
.links(graph.links);
function ticked() {
link
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
});
</script>