如何从节点和链接列表创建 d3 径向树

How to create a d3 radial-tree from a list of nodes and links?

本文关键字:d3 创建 列表 链接 节点      更新时间:2023-09-26

我使用以下密码查询从neo4j数据库中提取节点和关系:

match p=(:Root) <-[:linkedTo]- () 
unwind nodes(p) as n unwind rels(p) as r 
return {nodes: collect(distinct n), links: collect(distinct {source: id(endNode(r)), target: id(startNode(r))})}

我将查询结果转换为节点和链接数组,如下所示:

var obj = JSON.parse(xmlhttp.responseText);
var json = obj.data[0][0];
// Extract node list from neo4j/json data
var nodes = [];
for (n in json.nodes) {
    var nodeObj = json.nodes[n];
    var node = nodeObj.data;
    node.id = nodeObj.metadata.id;
    node.type = nodeObj.metadata.labels[0];
    nodes.push(node);
}
// Create a node map
var nodeMap = {};
nodes.forEach(function(x) { nodeMap['_'+x.id] = x; nodeMap['_'+x.id].children = []; });
// Extract link list from neo4j/json data
var links = json.links.map(function(x) {
        nodeMap['_'+x.source].children.push(nodeMap['_'+x.target]);
        return { source: nodeMap['_'+x.source], target: nodeMap['_'+x.target] };
    });

我应该如何在 d3 中从节点和链接生成树?Console.log(( 显示节点和链接数组都具有正确的格式,每个节点还包含其子节点的列表。

如上所述,节点和子节点的数据结构是正确的。缺少的部分是根节点。因此,我更改了密码查询以标识根节点,该根节点在我的图形中追加为根,如下所示:

match p=(:Panel) <-[:belongsTo]- (), (root:Panel {Name: "root"}) 
unwind nodes(p) as n unwind rels(p) as r 
return {root: id(root), nodes: collect(distinct n), links: collect(distinct {source: id(endNode(r)), target: id(startNode(r))})}

因此,该树按照 http://bl.ocks.org/d3noob/8324872 中的建议声明:

var tree = d3.layout.tree()
    .size([360, radius - 120]);
var diagonal = d3.svg.diagonal.radial()
    .projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
var vis = d3.select("#chart").append("svg")
    .attr("width", radius * 2)
    .attr("height", radius * 2 - 150)
    .append("g")
    .attr("transform", "translate(" + radius + "," + radius + ")");
// Compute the new tree layout starting with root
var root = nodeMap['_'+json.root];
var nodes = tree.nodes(root).reverse(), links = tree.links(nodes);
...

总而言之,诀窍是以 JSON 格式报告来自 neo4j 的根、节点和链接,然后构建节点数组、节点映射并根据链接将子节点分配给节点映射中的节点。