D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
ElaineYu
Full window
Github gist
Metis Stacked Bar Chart - Refugees 2015
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 width="960" height="500"></svg> <script> var margin = {top: 10, right: 20, bottom: 20, left: 60}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var y = d3.scaleLinear() .rangeRound([height, 0]); var x = d3.scaleBand() .rangeRound([0, width]) .paddingInner(0.05) .align(0.1); var z = d3.scaleOrdinal() .range(["rgb(170,164,225)", "rgb(66,69,94)", "rgb(144,74,191)", "rgb(240,155,241)", "rgb(216,21,180)", "rgb(142,46,92)", "rgb(47,101,208)", "rgb(66,32,240)", "rgb(254,206,95)", "rgb(116,53,2)", "rgb(251,202,185)", "rgb(203,44,9)", "rgb(254,143,6)", "rgb(168,121,98)", "rgb(253,137,146)", "rgb(251,32,118)"]); var g = d3.select("svg") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv("refugees.csv", function(data) { console.log('Original data', data); var keys = data.columns.slice(1); var yMax = d3.sum([3,497,1020,1625,3928,1405,2266,2235,1763,1284,762,472,254,141,146,77]); x.domain(data.map(function(d) { return d.Characteristic; })); y.domain([0, yMax+2000]); z.domain(keys); 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")) .append("text") .attr("x", 10) .attr("y", 20) .attr("dy", "0.32em") .attr("fill", "#000") .attr("font-weight", "bold") .attr("text-anchor", "start") .text("REFUGEES: INDIVIDUALS GRANTED ASYLUM AFFIRMATIVELY BY RELATIONSHIP TO PRINCIPAL APPLICANT "); g.append("g") .selectAll("g") .data(d3.stack().keys(keys)(data)) .enter().append("g") .attr("fill", function(d) { return z(d.key); }) .selectAll("rect") .data(function(d) { return d; }) .enter().append("rect") .attr("x", function(d) { return x(d.data.Characteristic); }) .attr("y", function(d) { return y(d[1]); }) .attr("height", function(d) { return y(d[0]) - y(d[1]); }) .attr("width", x.bandwidth()); var legend = g.append("g") .attr("font-family", "sans-serif") .attr("font-size", 10) .attr("text-anchor", "end") .selectAll("g") .data(keys.slice().reverse()) .enter().append("g") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); legend.append("rect") .attr("x", width - 19) .attr("width", 19) .attr("height", 19) .attr("fill", z); legend.append("text") .attr("x", width - 24) .attr("y", 9.5) .attr("dy", "0.32em") .text(function(d) { return d; }); }); </script> </body>
https://d3js.org/d3.v4.min.js