无法可视化 d3 强制布局中的节点

Can't visualize nodes in d3 force layout

我正在尝试将我的可视化脚本更改为更像 Modifying a Force Layout Example。由于我没有像 a, b and c 这样的固定节点要添加,所以我读取了 json file 来填充 nodeslinks 数组。

d3.json("mock.json", function(error, json) {
    if (error)
        throw error;
    nodes = nodes.concat(json.nodes);
    links = links.concat(json.links);
    start();
});

nodeslinks 大小合适,这意味着节点包含 26 nodes 和链接 37 links。现在我想简单地使用 linecircle 元素将它们可视化。

function start() {
    link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
    link.enter().append("line").attr("class", "link");
    link.exit().remove();

    node = node.data(force.nodes(), function(d) { return d.id;});
    node.enter().append("circle").attr("class", "node").attr("r", 8);
    node.exit().remove();
    force.start();
}

这与示例非常相似,我真的不明白为什么这行不通。我为 a demo 提供模拟。是因为我使用 concat() 而不是 push() 还是有其他问题?

您的代码:

d3.json("mock.json", function(error, json) {

    if (error)
        throw error;
    nodes = nodes.concat(json.nodes);
    links = links.concat(json.links);
    start();
});

必须像这样(原因 否则 force.nodes() 最初将设置为空数组):

d3.json("mock.json", function(error, json) {

    if (error)
        throw error;
    nodes = nodes.concat(json.nodes);
    links = links.concat(json.links);

    force.nodes(nodes); //else force.nodes() will be empty array set initially
    force.links(links)

    start();
});

下一个:

您的代码:

link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });

更正后的代码:

link = link.data(force.links(), function(d) { return d.source + "-" + d.target; });

工作代码here

希望对您有所帮助!