[英]How to create a d3 radial-tree from a list of nodes and links?
我使用以下cypher查詢從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()顯示節點和鏈接數組都具有正確的格式,每個節點還包含其子節點的列表。
如上所述,數據結構對於節點和子節點是正確的。 缺少的部分是根節點。 因此,我更改了cypher查詢以識別根節點,該節點在我的圖中追加為root,如下所示:
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的根,節點和鏈接,然后構建節點數組,節點映射並根據鏈接將子節點分配給節點映射中的節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.