D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
kcsluis
Full window
Github gist
Nesting
<!DOCTYPE html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .site { margin-bottom: 12px; } .info { font-family: sans-serif; font-size: 11px; display: inline-block; margin-right: 12px; } .bold { font-weight: bold; } </style> </head> <body> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script> <script> // reference: // https://bl.ocks.org/phoebebright/raw/3176159/ // https://bost.ocks.org/mike/nest/ d3.tsv("barley.tsv", ready); function ready(error, data) { if (error) return console.warn(error); // one-level nest var yieldsBySite = d3.nest() .key( function (d) { return d.site; }) .entries(data); // two-level nest var yieldsBySiteAndYear = d3.nest() .key( function (d) { return d.site; }) .key( function (d) { return d.year; }) .entries(data); // two-level nest with rollup, sorted var yieldsData = d3.nest() .key( function (d) { return d.site; }).sortKeys(d3.ascending) .key( function (d) { return d.year; }) .rollup( function (yields) { return { "total_yield": d3.sum(yields, function (d) { return d.yield; }) } }) .entries(data); console.log(yieldsData); // using nested data var site = d3.select('body').selectAll('div.site') .data(yieldsData) .enter() .append('div') .attr('class', 'site') .text( function (d) { return d.key; }); // data join inside the data join — data join inception var yearYields = site.selectAll('div.yield') .data( function (d) { return d.values; }) .enter() .append('div') .attr('class', 'yield'); yearYields.append('div') .attr('class', 'info') .text( function (d) { return d.key; }); yearYields.append('div') .attr('class', 'info bold') .text( function (d) { return Math.round(d.values.total_yield); }); }; </script>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js