UNPKG

dc

Version:

A multi-dimensional charting library built to work natively with crossfilter and rendered using d3.js

110 lines (94 loc) 3.44 kB
<!DOCTYPE html> <html lang="en"> <head> <title>dc.js - Table of Aggregated Data</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../css/dc.css"/> </head> <body> <div class="container"> <script type="text/javascript" src="header.js"></script> <div id="select-direction"> <label><input type=radio name="direction" value="descending" checked="true">&nbsp;descending</label> <label><input type=radio name="direction" value="ascending">&nbsp;ascending</label> </div> <table id="test"> <thead> <tr> <th>Expt</th> <th>#Run</th> <th>Avg(Speed)</th> </tr> </thead> </table> <script type="text/javascript" src="../js/promise-polyfill.js"></script> <script type="text/javascript" src="../js/fetch.umd.js"></script> <script type="text/javascript" src="../js/d3.js"></script> <script type="text/javascript" src="../js/crossfilter.js"></script> <script type="text/javascript" src="../js/dc.js"></script> <script type="text/javascript"> var chart = dc.dataTable("#test"); d3.csv("morley.csv").then(function(experiments) { /* Ordinarily a data table will show raw rows of data. But it can also show aggregated data, by passing a group as the dimension. This example creates a table that sorts the experiments from the highest average speed to the lowest average speed. The `avgGroup` produces the averages for each experiment. To display the items in descending order, just specify `.order(d3.descending)` and the data table will use `group.top()` to fetch the data. In order to display the items in ascending order, we need to create a "fake dimension" wrapping the group, because crossfilter groups don't have a `.bottom(N)` method https://github.com/dc-js/dc.js/wiki/FAQ#fake-dimensions */ var ndx = crossfilter(experiments), exptDimension = ndx.dimension(function(d) {return +d.Expt;}), avgGroup = exptDimension.group().reduce( function (p, v) { ++p.number; p.total += +v.Speed; p.avg = Math.round(p.total / p.number); return p; }, function (p, v) { --p.number; p.total -= +v.Speed; p.avg = (p.number == 0) ? 0 : Math.round(p.total / p.number); return p; }, function () { return {number: 0, total: 0, avg: 0} }); chart .width(768) .height(480) .showSections(false) .dimension(reversible_group(avgGroup)) .columns([function (d) { return d.key }, function (d) { return d.value.number }, function (d) { return d.value.avg }]) .sortBy(function (d) { return d.value.avg }) .order(d3.descending) chart.render(); function reversible_group(group) { return { top: function(N) { return group.top(N); }, bottom: function(N) { return group.top(Infinity).slice(-N).reverse(); } }; } d3.selectAll('#select-direction input') .on('click', function() { // this.value is 'ascending' or 'descending' chart.order(d3[this.value]).redraw() }); }); </script> </div> </body> </html>