D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
me1er
Full window
Github gist
stacked bar
Built with
blockbuilder.org
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>D3: Stack layout stacked bar chart</title> <script type="text/javascript" src="//d3js.org/d3.v4.js"></script> <style type="text/css"> /* No style rules here yet */ </style> </head> <body> <script type="text/javascript"> //Width and height var w = 500; var h = 300; //Original data var dataset = [ [ { x: "a", y: 5 }, { x: "b", y: 4 }, { x: "c", y: 2 }, { x: "d", y: 7 }, { x: "e", y: 23 } ], [ { x: "a", y: 10 }, { x: "b", y: 12 }, { x: "c", y: 19 }, { x: "d", y: 23 }, { x: "e", y: 17 } ], [ { x: "a", y: 22 }, { x: "b", y: 28 }, { x: "c", y: 32 }, { x: "d", y: 35 }, { x: "e", y: 43 } ] ]; //Set up stack method var stack = d3.stack().keys(["x","y"]); //Data, stacked stack(dataset); //Set up scales var yScale = d3.scaleBand() .domain(d3.range(0, dataset[0].length)) .rangeRound([h, 0]) .padding(0.3); var xScale = d3.scaleLinear() .domain([0, d3.max(stack(dataset), function(d) { return d3.max(d, function(d) { return d.y; }); }) ]) .range([0,w]); //Easy colors accessible via a 10-step ordinal scale //var colors = d3.scale.category10(); var colors = d3.scaleOrdinal() .range(["#EA4424", "#008DD2", "#00A859", "#FDBA02", "#565656", "#C5B3A5"]); //Create SVG element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); // Add a group for each row of data var groups = svg.selectAll("g") .data(dataset) .enter() .append("g") .style("fill", function(d, i) { return colors(i); }); // Add a rect for each data value var rects = groups.selectAll("rect") .data(function(d) { return d; }) .enter() .append("rect") .attr("y", function(d, i) { return yScale(i); }) .attr("x", function(d) { return xScale(d.y0); }) .attr("width", function(d) { return xScale(d.y); }) .attr("height", yScale.bandwidth); </script> </body> </html>
https://d3js.org/d3.v4.js