Skip to content

Instantly share code, notes, and snippets.

@fogonwater
Last active December 8, 2017 23:21
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 fogonwater/329eee8d1981a04160564fbefbe477d8 to your computer and use it in GitHub Desktop.
Save fogonwater/329eee8d1981a04160564fbefbe477d8 to your computer and use it in GitHub Desktop.
simple circle packing
license: mit
height: 960
We can make this file beautiful and searchable if this error is corrected: It looks like row 2 should actually have 3 columns, instead of 2. in line 1.
id,parentId,size
cars,
owned,cars
traded,cars
learned,cars
pilot,owned,40
325ci,owned,40
accord,owned,20
chevette,traded,10
odyssey,learned,20
maxima,learned,10
another,learned,15
more,learned,5
lone,cars,55
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chroma-js/1.3.4/chroma.min.js"></script>
<style>
body { margin:0;top:0;right:0;bottom:0;left:0; }
svg { font-family: Courier; }
.annotation-note-title, text.title { font-weight: bold; }
text.title { font-size: 1.2em; }
</style>
</head>
<body>
<svg width="960" height="960">
<text class="title" x=40 y=50>simple d3.pack()</text>
<g transform="translate(1,1)"></g>
</svg>
<script>
const svg = d3.select("svg"),
width = +svg.attr("width"),
height= +svg.attr("height"),
color = chroma
.scale(['#ED9367','#FAE8CB'])
.mode('lch')
.colors(3)
const g = svg.append("g")
const layout = d3.pack()
.size([width - 2, height - 2])
.padding(6)
// Get the data from our CSV file
d3.csv('data.csv', function(error, data) {
data.sort(function(x, y){ return d3.ascending(x.size, y.size) })
if (error) throw error;
const stratData = d3.stratify()(data),
root = d3.hierarchy(stratData)
.sum(function (d) { return d.data.size })
.sort(function(a, b) { return b.value - a.value }),
nodes = root.descendants()
layout(root)
const slices = g.selectAll('circle')
.data(nodes)
.enter()
.append('circle')
.attr('cx', function (d) { return d.x; })
.attr('cy', function (d) { return d.y; })
.attr('r', function (d) { return d.r; })
.style("fill", function(d) { return color[d.depth]; })
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment