D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
Ctuauden
Full window
Github gist
transition 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> <script> var n = 10, // number of samples m = 5; // number of series var data = d3.range(m).map(function() { return d3.range(n).map(Math.random); }); var margin = {top: 20, right: 30, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var y = d3.scaleLinear() .domain([0, n]) .rangeRound([height, 0]) .nice(); var yMax = d3.max(data, function(d) { return d3.max(d); }); var x = d3.scaleBand() .rangeRound([0, width]) .paddingInner(0.05) .align(0.1) .domain(d3.range(n)); var x1 = d3.scaleBand() .domain(d3.range(m)) .range([0, x.bandwidth() - 10]); var z = d3.scaleOrdinal() .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); var ChartType = 'stacked'; var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.selectAll("body").on("click",function(){ if(ChartType==="stacked"){ChartType = "grouped",DessinerGraphique(data,ChartType);} else{ChartType="stacked",DessinerGraphique(data,ChartType);} }); svg.append("g").selectAll("g") .data(data) .enter().append("g") .style("fill", function(d, i) { return z(i); }) .attr("transform", function(d, i) { return "translate(" + x1(i) + ",0)"; }) .selectAll("rect") .data(function(d) { return d; }) .enter().append("rect") .attr("width", x1.bandwidth()) .attr("height", y) .attr("x", function(d, i) { return x(i); }) .attr("y", function(d) { return height - y(d); }); function DessinerGraphique(data,type){ if (type==="stacked"){ console.log("stacké") y.domain([0, n]); } if (type==="grouped"){ y.domain([0, yMax]); svg.selectAll('rect').data(data) .transition() .duration(500) .delay(function(d, i) { return i * 10; }) .attr("x", function(d, i) { return x(i) + x.bandwidth() / n * this.parentNode.__data__.key; }) .attr("width", x.bandwidth() / n) .transition() .attr("y", function(d) { return y(d[1] - d[0]); }) .attr("height", function(d) { return y(0) - y(d[1] - d[0]); }); console.log("groupé") } } </script> </body>
https://d3js.org/d3.v4.min.js