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

I am retrieving nodes and relations from neo4j database using the following cypher query: match p = (: Root) <- [: linkedTo] - () unwind nodes (p) when n unwinds rels (p) as r return {nodes: collect (distinct n), links: collect (distinct {source: id (endNode (r)), target: id (startNode (r))})}

I am converting the query result to arrays of nodes and links like this:

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] };
    });

      

How do I generate a tree in d3 from nodes and links? Console.log () shows that both the node and link arrays are in the correct format, each node also contains a list of its children.

+3


source to share


1 answer


As mentioned above, the data structure was correct with nodes and children. The missing piece was the root node. So I modified the cypher query to determine the root node that is appended to the root name in my graph like below:

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))})}

      

Hence the tree is declared as suggested at 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);
...

      

So the trick is to report root, nodes and links from neo4j in JSON format, and then build a node array, map node and assign child nodes in the map node based on links.

+2


source







All Articles