D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
williaster
Full window
Github gist
Linked charts using Square's crossfilter.js library
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Cereal Sugar by Manufacturer</title> <!-- References to d3 and crossfilter libraries here --> <script src="./d3.min.js" charset="utf-8"></script> <script src="./crossfilter.min.js"></script> <!-- Must be loaded before dc.min.js --> <script src="./dc.min.js" charset="utf-8"></script> <!-- Styles --> <link rel="stylesheet" type="text/css" href="./dc.css"/> <style> .title { font-weight: bold; margin: 50px 0 50px 100px; } .dc-chart g.row text { fill: black; font-weight: bold; } #chart-manufacturers g.row rect { fill: steelblue; } #chart-manufacturers g.row rect.deselected { fill: #aaa; } </style> </head> <body> <div id="chart-manufacturers"> <div class="title"># Cereals By Manufacturer</div> </div> <div id="chart-sugars"> <div class="title"># Cereals By Sugar Content</div> </div> <script> // Load data d3.csv('./cereal-detailed.csv', function(error, cerealData) { var numericFields = ["calories", "protein", "fat", "sodium", "fiber", "carbs", "sugars", "potassium", "vitamins"]; // Type coercion, absolutely necessary for crossfilter! cerealData.forEach(function(cerealObj, i) { numericFields.forEach(function(field) { cerealObj[field] = +cerealObj[field]; // to number }); }); // Make charts createLinkedCharts(cerealData); }); var createLinkedCharts = function(cerealData) { // create the crossfilter and relevant dimensions / groups var cerealCF = crossfilter(cerealData), sugarDimension = cerealCF.dimension(function(cerealObj) { return cerealObj.sugars; }), manufDimension = cerealCF.dimension(function(cerealObj) { return cerealObj.manufacturer; }); var cerealsPerManufacturer = manufDimension .group() .reduceCount(); var cerealsPerSugar = sugarDimension .group() .reduceCount(); // then charts, initialized by passing them a DOM div id as container var manufacturerRowChart = dc.rowChart("#chart-manufacturers") .width(400) .height(180) .margins({top: 10, right: 50, bottom: 30, left: 40}) .dimension(manufDimension) .group(cerealsPerManufacturer) .elasticX(true); var sugarBarChart = dc.barChart("#chart-sugars") .width(400) .height(190) .margins({top: 10, right: 50, bottom: 30, left: 40}) .dimension(sugarDimension) .group(cerealsPerSugar) .x( d3.scale .linear() .domain( d3.extent(cerealData, function(cObj) { return cObj.sugars; }) )) .elasticY(true) .xAxisLabel('Sugar (g)'); dc.renderAll(); }; </script> </body> </html>