Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active January 13, 2022 23:01
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/3184089 to your computer and use it in GitHub Desktop.
Tree Layout Orientations
license: gpl-3.0
{
"children": [
{
"children": [
{},
{}
]
}
]
}
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #000;
}
.border {
fill: none;
shape-rendering: crispEdges;
stroke: #aaa;
}
.node {
stroke: #fff;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 140, right: 10, bottom: 140, left: 10},
width = 240 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var orientations = {
"top-to-bottom": {
size: [width, height],
x: function(d) { return d.x; },
y: function(d) { return d.y; }
},
"right-to-left": {
size: [height, width],
x: function(d) { return width - d.y; },
y: function(d) { return d.x; }
},
"bottom-to-top": {
size: [width, height],
x: function(d) { return d.x; },
y: function(d) { return height - d.y; }
},
"left-to-right": {
size: [height, width],
x: function(d) { return d.y; },
y: function(d) { return d.x; }
}
};
var svg = d3.select("body").selectAll("svg")
.data(d3.entries(orientations))
.enter().append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("rect")
.attr("width", width)
.attr("height", height)
.attr("class", "border");
svg.append("text")
.attr("x", 6)
.attr("y", 6)
.attr("dy", ".71em")
.text(function(d) { return d.key; });
d3.json("graph.json", function(error, root) {
if (error) throw error;
svg.each(function(orientation) {
var svg = d3.select(this),
o = orientation.value;
// Compute the layout.
var tree = d3.layout.tree().size(o.size),
nodes = tree.nodes(root),
links = tree.links(nodes);
// Create the link lines.
svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", d3.svg.diagonal().projection(function(d) { return [o.x(d), o.y(d)]; }));
// Create the node circles.
svg.selectAll(".node")
.data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 4.5)
.attr("cx", o.x)
.attr("cy", o.y);
});
});
</script>
@krish85
Copy link

krish85 commented Mar 7, 2019

do we have V4 version of this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment