Skip to content

Instantly share code, notes, and snippets.

@jiankuang
Last active May 29, 2016 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiankuang/2addc9c0c5cea5370a5535270c874531 to your computer and use it in GitHub Desktop.
Save jiankuang/2addc9c0c5cea5370a5535270c874531 to your computer and use it in GitHub Desktop.
D3 Layout Tree
<body>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var chart = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform", "translate(50, 50)");
var tree = d3.layout.tree()
.size([400, 400]);
d3.json("myknowledgedomain.json", function(data) {
var nodes = tree.nodes(data); // create data nodes suitable for tree structure
var links = tree.links(nodes); // create links to connect source(parent) and target(child) nodes
var nodes = chart.selectAll(".node")
.data(nodes).enter()
.append("g")
.attr("class", "node")
.attr("transform", function(d){ return "translate(" + d.y + "," + d.x + ")"; }); // flip x and y of nodes
nodes.append("circle")
.attr("r", 5)
.attr("fill", "steelblue");
nodes.append("text")
.text(function(d){ return d.name; });
var diagonal = d3.svg.diagonal()
.projection(function(d){ return [d.y, d.x]; }); // flip x and y of links
chart.selectAll(".link")
.data(links).enter()
.append("path")
.attr("class", "link")
.attr("fill", "none").attr("stroke", "#ADADAD")
.attr("d", diagonal);
});
</script>
</body>
{
"name": "Data Development",
"children": [
{
"name": "Data Visualization",
"children": [
{"name": "D3.js"},
{"name": "Dimple.js"},
{"name": "matplotlib(python)"},
{"name": "ggplot(R)"}
]
},
{
"name": "Data Analysis",
"children": [
{"name": "numpy"},
{"name": "scikit-learn"}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment