Skip to content

Instantly share code, notes, and snippets.

@infinnie
Last active October 29, 2018 08:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save infinnie/fe916ff1141c1412a6258472abc8af6e to your computer and use it in GitHub Desktop.
Save infinnie/fe916ff1141c1412a6258472abc8af6e to your computer and use it in GitHub Desktop.
Tree to D3 chart
function treeGraph(t){
var resultPoints=[],resultLines=[];
resultPoints.push({name:t.name});
if(t.children){
t.children.forEach(function(ct){
var childResult=treeGraph(ct);
resultLines.push({
source: t.name,
target: ct.name
});
resultPoints.push.apply(resultPoints, childResult.points);
resultLines.push.apply(resultLines,childResult.lines);
});
}
return {
points: resultPoints,
lines: resultLines
};
}
function graphPos(x){
return x*3+400;
}
var tree={
name:"Primates",
children:[
{
name:"Strepsirrhini",
children:[
{
name:"Lemuriformes",
children: [
{name:"Lemuroidea"},
{name:"Lorisoidea"}
]
}
]
},
{
name:"Haplorhini",
children:[
{name:"Tarsiiformes"},
{
name:"Simiiformes",
children:[
{name:"Platyrrhini"},
{
name:"Catarrhini",
children: [
{name:"Cercopithecidae"},
{
name:"Hominoidea",
children:[
{name:"Hylobatidae"},
{name:"Hominidae"}
]
}
]
}
]
}
]
}
]
};
var resultGraph=treeGraph(tree);
var nodes=resultGraph.points,
elements=d3.select("#result").selectAll("circle").data(nodes).enter()
.append("circle").attr("r",15).attr("fill","#d5d5d5").attr("opacity",0).on("click",function(e,i){
sim.alpha(.8).restart();
nodes[i].vx=-nodes[i].x;
nodes[i].vy=-nodes[i].y;
}),
lines=d3.select("#result").selectAll("line").data(resultGraph.lines).enter().append("line"),
texts=d3.select("#result").selectAll("text").data(nodes).enter().append("text").text(function(x){
return x.name;
});
sim=d3.forceSimulation(nodes)
.alphaDecay(.005)
.force("pos",d3.forceManyBody().strength(-10))
.force("center",d3.forceCenter())
.force("link",d3.forceLink().id(function(x){return x.name;}).links(resultGraph.lines))
.force("x",d3.forceX().strength(.01)).force("y",d3.forceY().strength(.01))
.on("tick",function(){
elements.attr("cx",function(node){
return graphPos(node.x)
}).attr("cy",function(node){
return graphPos(node.y)
}).attr("opacity",1);
lines.attr("x1",function(d){return graphPos(d.source.x)})
.attr("x2",function(d){return graphPos(d.target.x)})
.attr("y1",function(d){return graphPos(d.source.y)})
.attr("y2",function(d){return graphPos(d.target.y)})
.attr("stroke","#000").attr("strokeWidth",2);
texts.attr("x",function(node){
return graphPos(node.x)+24;
}).attr("y",function(node){
return graphPos(node.y)+4;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment