我在这里使用Mike Bostock的例子:https://bl.ocks.org/mbostock/4062045
修改了html以导出json文件中的节点和链接。不幸的是我无法上传整个文件,但这里有一些示例行:
{"nodes":[
{"id":"Myriel","group":1,"index":0,"x":791.0400812247225, "y":533.3621312414037,vy":-2.3537711995332984,"vx":-4.361299434636218},
{"id":"Napoleon","group":1,"index":1,"x":761.1221752922569, "y":563.7517203508193,"vy":-2.3317798484016428,"vx":-4.346736342960801},
.
.
.
"links":[{
"source":
{"id":"Napoleon","group":1,"index":1,"x":761.1221752922569, "y":563.7517203508193,"vy":-2.3317798484016428,"vx":-4.346736342960801},
"target":
{"id":"Myriel","group":1,"index":0,"x":791.0400812247225, "y":533.3621312414037,"vy":-2.3537711995332984,"vx":-4.361299434636218},
"value":1,"index":0},
.
.
.
我想要做的是阅读另一个html文件中的节点和链接,然后只显示它。
我认为通过用xy_miserables.json替换输入文件miserables.json文件,这应该是直截了当的。我注意到的第一件事是节点没有连接到链路,第二件事是节点分开但链路保持固定。我能够更改模拟参数,使节点保持接近原始位置。但是我如何将链接连接到他们的节点? 这是html内容:
<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("charge", d3.forceManyBody())
//.force("center", d3.forceCenter(width / 2, height / 2));
d3.json("./xy_miserables.json", function(error, graph) {
if (error) throw error;
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); });
node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 5)
.attr("fill", function(d) { return color(d.group); })
.attr("x", function(d) {return d.x})
.attr("y", function(d) {return d.y});
console.log(graph.links)
simulation.force("link")
.links(graph.links);
simulation
.nodes(graph.nodes)
.on("tick", ticked);
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>
我确认链接已定义了正确的源ID和目标ID。我将链接信息与原始数据进行了比较,看起来很好。 我在这忘记了什么?
非常感谢您提前, 马库斯
答案 0 :(得分:0)
经过一些测试后,我意识到问题在于我正在尝试读取的导出的xyz文件。我从miserables.json文件开始,系统地添加了节点和链接属性。事实证明,不需要任何链接属性。这是我的json文件的最终解决方案:
{
"nodes": [
{"id": "1", "property1": "propert1", "property2": "property2", "property3": "property3", "x": "999.772419601515", "y": "597.0467800520148", "vx": "0", "vy": "0", "fx": "999.772419601515", "fy": "597.0467800520148"},
{"id": "2", "property1": "propert1", "property2": "property2", "property3": "property3", "x": "999.772419601515", "y": "597.0467800520148", "vx": "0", "vy": "0", "fx": "999.772419601515", "fy": "597.0467800520148"},....],
"links": [
{"source": "1", "target": "2, "value": 1},
{"source": "1", "target": "3", "value": 1},....]
}
现在我的链接已连接到节点。 干杯, 马库斯