D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
scotthmurray
Full window
Github gist
Crops planted 1929-2015 (not working)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Stack layout, stacked bar chart, but flipped</title> <script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script> <style type="text/css"> body { background-color: gray; } svg { background-color: white; } </style> </head> <body> <h1>Crop acres planted 1929-2015</h1> <p>This is a subhead that goes here. Source: USDA</p> <script type="text/javascript"> var w = 800; var h = 500; // planned out what each data should look like // { // crop: "Corn", // acres: [ // { x: "1929", y: 12.34 }, // { x: "1930", y: 56.78 }, // { x: "1931", y: 90.12 }, // … // ] // } d3.csv("cropsVertical.csv", function(data) { console.log(data); //all arrays have a map function // var dataset = data.map(function(d,i) { // return {x:d.year, y: d.corn} // }) // console.log(dataset) var newData = [] // d3 helper maps out object keys // {year: "1929", corn: "99.13", soy: "2.43", wheat: "67.18", sorghum: "3.52"} var keys = d3.keys(data[0]) console.log(keys); // Arrays have a forEach function keys.forEach (function(k,i) { if (k != "year") { //console.log(k) var innerData = data.map(function(d) { return { x: +d.year, y: +d[k] }; }) //console.log(innerData) // adding each data to data array newData.push({crop: k, acres: innerData}) //console.log(newData) } }); //Set up stack method var stack = d3.layout.stack() .values(function(d) { return d.acres; }) .order("reverse"); //Flip the order //Data, stacked stack(newData); console.log(newData); //Set up scales var xScale = d3.scale.ordinal() .domain(d3.range(data[0].length)) .rangeRoundBands([0, w], 0.05); var yScale = d3.scale.linear() .domain([0, d3.max(data, function(d) { return d3.max(d, function(d) { return d.y0 + d.y; }); }) ]) .range([0, h]); //Easy colors accessible via a 10-step ordinal scale var colors = d3.scale.category10(); //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(newData) .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("x", function(d, i) { return xScale(i); }) .attr("width", xScale.rangeBand()) .attr("y", function(d) { return h - yScale(d.y0) - yScale(d.y); //Flip the math! }) .attr("height", function(d) { return yScale(d.y); }); }); </script> </body> </html>
https://d3js.org/d3.v3.min.js