D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
tvachon
Full window
Github gist
D3 v4 100% stacked chart
forked from
tvachon
's block:
Grouped Stacked Chart
<!DOCTYPE html> <h1> Example of a 100% stacked chart using D3 v4 </h1> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } rect { stroke: #fff; } </style> <svg width="900" height="400"></svg> <script src="//d3js.org/d3.v4.min.js"></script> <script> var svg = d3.select("svg"), margin = {top: 20, right: 60, bottom: 30, left: 40}, width = +svg.attr("width") - margin.left - margin.right, height = +svg.attr("height") - margin.top - margin.bottom, g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var x = d3.scaleBand() .rangeRound([0, width]) .padding(0.5) .align(0.1); var y = d3.scaleLinear() .rangeRound([height, 0]); var z = d3.scaleOrdinal() .range(["#D8666A","#F4865F","#FFD774","#C9E068","#5DB575"]); var stack = d3.stack() .offset(d3.stackOffsetExpand); d3.csv("data.csv", type, function(error, data) { if (error) throw error; data.sort(function(a, b) { return b[data.columns[1]] / b.total - a[data.columns[1]] / a.total; }); x.domain(data.map(function(d) { return d.PerformanceBand; })); z.domain(data.columns.slice(1)); var serie = g.selectAll(".serie") .data(stack.keys(data.columns.slice(1))(data)) .enter().append("g") .attr("class", "serie") .attr("fill", function(d) { return z(d.key); }); serie.selectAll("rect") .data(function(d) { return d; }) .enter().append("rect") .attr("x", function(d) { return x(d.data.PerformanceBand); }) .attr("y", function(d) { return y(d[1]); }) .attr("height", function(d) { return y(d[0]) - y(d[1]); }) .attr("width", x.bandwidth()); g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); g.append("g") .attr("class", "axis axis--y") .call(d3.axisLeft(y).ticks(10, "%")); var legend = serie.append("g") .attr("class", "legend") .attr("transform", function(d) { var d = d[d.length - 1]; return "translate(" + (x(d.data.PerformanceBand) + x.bandwidth()) + "," + ((y(d[0]) + y(d[1])) / 2) + ")"; }); legend.append("line") .attr("x1", -6) .attr("x2", 6) .attr("stroke", "#000"); legend.append("text") .attr("x", 9) .attr("dy", "0.35em") .attr("fill", "#000") .style("font", "10px sans-serif") .text(function(d) { return d.key; }); }); function type(d, i, columns) { for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]]; d.total = t; return d; } </script>
https://d3js.org/d3.v4.min.js