D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
hbthanki
Full window
Github gist
Grouped_Stacked
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <svg class="chart" width="900" height="500"></svg> <script> var svg = d3.select(".chart"), margin = {top: 20, right: 20, bottom: 30, left: 100}, 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.scaleLinear() .rangeRound([0, width]); var y = d3.scaleBand() .rangeRound([0, height]) .paddingInner(0.05); var z = { 'a': d3.scaleOrdinal() .range(["#8cb6d9", "#4787ba", "#216297"]), 'b': d3.scaleOrdinal() .range(["#ff5555", "#ff1122", "#990022"]), 'c': d3.scaleOrdinal() .range(["#d6d6d6", "#919191", "#444342"]) }; d3.csv("data.csv", function(d, i, columns) { for (i = 2, t = 0; i < columns.length; ++i){ d[columns[i]] = +d[columns[i]]; t += d[columns[i]]; } d.total = t; return d; }, function(error, data) { if (error) throw error; var keys = data.columns.slice(2); data.sort(function(a, b) { return b.total - a.total; }); //setting domains x.domain([0, d3.max(data, function(d){ return d.total; }) ]).nice(); y.domain(data.map(function(d){ return d.Name; }) ); for (key in z){ z[key].domain(key); } //drawing chart g.append("g") .selectAll("g") .data(d3.stack().keys(keys)(data)) .enter().append("g") .selectAll("rect") .data(d => d) .enter().append("rect") .attr("fill", function(d, i) { var key = d3.select(this.parentNode).datum().key; return z[d.data.team](key); }) .attr("x", function(d){ return x(d[0]); }) .attr("y", function(d){ return y(d.data.Name); }) .attr("height", function(d){ return y.bandwidth(); }) .attr("width", function(d){ return x(d[1]) - x(d[0]); }); g.append("g") .attr("class", "axis") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); g.append("g") .attr("class", "axis") .call(d3.axisLeft(y).ticks(null, "s")); }); </script> </body>
https://d3js.org/d3.v4.min.js