D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
erikhazzard
Full window
Github gist
index
<!DOCTYPE html> <html> <head> <title>Simple Stack</title> <style> svg { border: solid 1px #ccc; font: 10px sans-serif; shape-rendering: crispEdges; } </style> </head> <body> <input type='button' value='Update' id='update' /> <div id="viz"></div> <script src='/static/lib/all3rdjs.min.js'></script> <script type="text/javascript"> var w = 960, h = 500 // create canvas var svg = d3.select("#viz").append("svg:svg") .attr("class", "chart") .attr("width", w) .attr("height", h ) .append("svg:g") .attr("transform", "translate(10,470)"); var generateMatrix = function(){ var getNum = function(){ return Math.random() * 10000; } var matrix = [ [ 1, getNum(), getNum(), getNum()], [ 2, getNum(), getNum(), getNum()], [ 3, getNum(), getNum(), getNum()], [ 4, getNum(), getNum(), getNum()], [ 5, getNum(), getNum(), getNum()] ]; return matrix; } var update = function(){ x = d3.scale.ordinal().rangeRoundBands([0, w-50]) y = d3.scale.linear().range([0, h-50]) z = d3.scale.ordinal().range(["darkblue", "blue", "lightblue"]) // 4 columns: ID,c1,c2,c3 var matrix = generateMatrix(); var remapped =["c1","c2","c3"].map(function(dat,i){ return matrix.map(function(d,ii){ return {x: ii, y: d[i+1] }; }) }); var stacked = d3.layout.stack()(remapped) x.domain(stacked[0].map(function(d) { return d.x; })); y.domain([0, d3.max(stacked[stacked.length - 1], function(d) { return d.y0 + d.y; })]); // Add a group for each column. var valgroup = svg.selectAll("g.valgroup") .data(stacked) .enter().append("svg:g") .attr("class", "valgroup") .style("fill", function(d, i) { return z(i); }) .style("stroke", function(d, i) { return d3.rgb(z(i)).darker(); }); // Add a rect for each date. var rect = valgroup.selectAll("rect") .data(function(d){return d;}) rect.enter().append("svg:rect") .attr("x", function(d) { return x(d.x); }) .attr("y", function(d) { return h; }) .attr("height", function(d) { return 0; }) .attr("width", x.rangeBand()); rect.transition() .duration(250).ease("quad") .attr("x", function(d) { return x(d.x); }) .attr("y", function(d) { return -y(d.y0) - y(d.y); }) .attr("height", function(d) { return y(d.y); }) .attr("width", x.rangeBand()) }; //Update on click d3.select('#update').on('click', update); </script> </body> </html>