Skip to content

Instantly share code, notes, and snippets.

@valex
Created November 24, 2017 19:48
Show Gist options
  • Save valex/6fae0e94d70fc84f08feb76809b490f5 to your computer and use it in GitHub Desktop.
Save valex/6fae0e94d70fc84f08feb76809b490f5 to your computer and use it in GitHub Desktop.
Pack diagram, d3.js version 4
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
<script>
var url = 'https://gist.githubusercontent.com/d3byex/25129228aa50c30ef01f/raw/11fe9418fba81e254ad0f629b592f9e33c3241c6/sales_rollup.json';
d3.json(url, function(error, data) {
var diameter = 500;
var svg = d3.select('body')
.append('svg')
.attrs({
width: diameter,
height: diameter
});
var pack = d3.pack()
.size([diameter, diameter]);
var root = d3.hierarchy(data);
var nodes = svg.datum(data)
.selectAll('g')
.data(pack(root).descendants())
.enter()
.append('g')
.attr('transform', function (d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
nodes.append('circle')
.each(function (d) {
d3.select(this)
.attrs({
r: d.r,
fill: d.children ? 'rgb(31, 119, 180)' : '#ff7f0e',
'fill-opacity': d.children ? 0.25 : 1.0,
stroke: d.children ? 'rgb(31, 119, 180)' : 'none'
});
});
nodes.filter(function (d) {
return !d.children;
})
.append('text')
.attr('dy', '.3em')
.styles({
'text-anchor': 'middle',
'font': '8px sans-serif'
})
.text(function (d) {
return d.data.name.substring(0, d.r / 3);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment