Skip to content

Instantly share code, notes, and snippets.

@denjn5
Last active September 27, 2017 10:49
Show Gist options
  • Save denjn5/53a2495557cb9695322adc9ddbd133fd to your computer and use it in GitHub Desktop.
Save denjn5/53a2495557cb9695322adc9ddbd133fd to your computer and use it in GitHub Desktop.
Simple Tree (d3 v4; JSON; 62 Lines)
license: gpl-3.0
height: 200
border: no

This is the simplest horizontal tree diagram I could create (using JSON, which immediately adds some syntax overhead). I prefer the version that pulls from CSV. Let me know if you think I can make it tighter.

Build notes:

  • To differentiate between local variables and framework objects, I prefix variables with lowercase 'v'.

From https://bl.ocks.org/denjn5/53a2495557cb9695322adc9ddbd133fd

{
"id": "cars", "children": [{
"id": "owned",
"children": [{"id": "pilot", "size": 40}, {"id": "325ci", "size": 20}, {"id": "accord", "size": 2}]
}, {
"id": "traded",
"children": [{"id": "chevette", "size": 1}]
}, {
"id": "learned",
"children": [{"id": "odyssey", "size": 20}, {"id": "maxima", "size": 5}]
}]
}
<!DOCTYPE html>
<meta charset='utf-8'>
<head>
<title>Simple Tree (d3 v4; JSON; 63 Lines)</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<style>
circle {
stroke: #05668D;
fill: white;
opacity: 0.6;
stroke-width: 2px;
}
path {
fill: none;
stroke: #05668D;
opacity: 0.6;
stroke-width: 2px;
}
</style>
<svg>
<g></g>
</svg>
<script>
var vWidth = 300;
var vHeight = 200;
// Prepare our physical space
var g = d3.select('svg').attr('width', vWidth).attr('height', vHeight)
.select('g').attr('transform', 'translate(20,20)');
// Get the data from our CSV file
d3.json('data.json', function(error, vData) {
if (error) throw error;
drawViz(vData);
});
function drawViz(vData) {
// Declare d3 layout
var vLayout = d3.tree().size([vHeight * 0.9, vWidth * 0.8]);
// Layout + Data
var vRoot = d3.hierarchy(vData);
var vNodes = vRoot.descendants();
var vLinks = vLayout(vRoot).links();
// Draw on screen
g.selectAll('path').data(vLinks).enter().append('path')
.attr('d', d3.linkHorizontal()
.x(function(d) { return d.y; })
.y(function(d) { return d.x; }));
g.selectAll('circle').data(vNodes).enter().append('circle')
.style('r', 10)
.attr('transform', function (d) { return 'translate(' + d.y + ',' + d.x + ')'; });
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment