javascript - How to convert to D3's JSON format? -
while following numerous d3 examples, data gets formatted in format given in flare.json:
{ "name": "flare", "children": [ { "name": "analytics", "children": [ { "name": "cluster", "children": [ {"name": "agglomerativecluster", "size": 3938}, :
i have adjacency list follows:
a1 a2 a2 a3 a2 a4
which want convert above format. currently, doing on server-side there way achieve using d3's functions? found 1 here, approach seems require modification of d3 core library not in favor due maintainability. suggestions?
there's no prescribed format, can redefine data through various accessor functions (such hierarchy.children) , array.map. format quoted convenient representation trees because works default accessors.
the first question whether intend display graph or tree. graphs, data structure defined in terms of nodes , links. trees, input layout root node, may have array of child nodes, , leaf nodes have associated value.
if want display graph, , have list of edges, you'll want iterate on edges in order produce array of nodes , array of links. had file called "graph.csv":
source,target a1,a2 a2,a3 a2,a4
you load file using d3.csv , produce array of nodes , links:
d3.csv("graph.csv", function(links) { var nodesbyname = {}; // create nodes each unique source , target. links.foreach(function(link) { link.source = nodebyname(link.source); link.target = nodebyname(link.target); }); // extract array of nodes map name. var nodes = d3.values(nodebyname); function nodebyname(name) { return nodesbyname[name] || (nodesbyname[name] = {name: name}); } });
you can pass these nodes , links force layout visualize graph:
if want produce tree instead, you'll need different form of data transformation accumulate child nodes each parent.
d3.csv("graph.csv", function(links) { var nodesbyname = {}; // create nodes each unique source , target. links.foreach(function(link) { var parent = link.source = nodebyname(link.source), child = link.target = nodebyname(link.target); if (parent.children) parent.children.push(child); else parent.children = [child]; }); // extract root node. var root = links[0].source; function nodebyname(name) { return nodesbyname[name] || (nodesbyname[name] = {name: name}); } });
like so:
Comments
Post a Comment