Mike Bostock's Stacked-to-Grouped example showcases a data generation method that I find intriguing. However, since I have my own data stored in a CSV file, my main focus is on deciphering his approach and adapting it to work with my data instead.
// Inspired by Lee Byron's test data generator.
function bumpLayer(n, o) {
function bump(a) {
var x = 1 / (.1 + Math.random()),
y = 2 * Math.random() - .5,
z = 10 / (.1 + Math.random());
for (var i = 0; i < n; i++) {
var w = (i / n - y) * z;
a[i] += x * Math.exp(-w * w);
}
}
var a = [], i;
for (i = 0; i < n; ++i) a[i] = o + o * Math.random();
for (i = 0; i < 5; ++i) bump(a);
return a.map(function(d, i) { return {x: i, y: Math.max(0, d)}; });
}
Understanding this code, especially when manipulated as shown below, can be challenging:
n = 6, // number of layers
m = 12, // number of samples per layer
stack = d3.layout.stack(),
layers = stack(d3.range(n).map(function() { return bumpLayer(m, .1); })),
To see the steps in action, check out my working code example here:
GOAL: My objective is to transform my csv file into a 2D array that can be processed by d3.
Although the following snippet doesn't work for me, it serves as a starting point:
// store the names of each column in csv file in array
var headers = ["Under $1000","$1000-$9999","$10000-19999","$20000-99999","100K - $999999","Over $1 Million"];
var myData = function(mycsv){
d3.layout.stack()(headers
.map(function(value){
return mycsv.map(function(d) {
return {x: d.Category, y: +d[value]};
});
}))
};
Thank you!
*EDIT***
In another example using d3.layout.stack() and csv, the parsing code looks like this:
d3.csv("crimea.csv", function(crimea) {
// Transpose the data into layers by cause.
var causes = d3.layout.stack()(["wounds", "other", "disease"].map(function(cause) {
return crimea.map(function(d) {
return {x: parse(d.date), y: +d[cause]};
});
}));
// Compute the x-domain (by date) and y-domain (by top).
x.domain(causes[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(causes[causes.length - 1], function(d) { return d.y0 + d.y; })]);
Check out the example here: http://bl.ocks.org/mbostock/1134768