score:4

i was having the same problem. after all i came with the following solution:

``````data.foreach(function (d) {
var newd = {x: d[xcoord]};
var y0neg = 0;
var y0pos = 0;
newd.values = color.domain().map(function (m) {
if (d[m] > 0)
return { name: m, y0: y0pos, y1: y0pos += +d[m] };
else {
var y1 = y0neg;
return { name: m, y0: y0neg += d[m], y1: y1 };
}
});
newd.totalpositive = d3.max(newd.values, function (v) { return v.y1});
newd.totalnegative = d3.min(newd.values, function (v) { return v.y0 });
arranged.push(newd);
});
``````

this is the way to arrange your data. i suppose that the variable d holds the values for each item for given x coordinate. the data collection is a list of values such as:

``````{
'xcoord':'january',
'gains': 100,
'othergains':20,
'loses': -50
}
``````

the names of the items to be show have to be mapped to the domain and then for each month we have to aggregate the data. for each item in given month i have a y0 and y1 coordinate. we have to have separate counter for negative and positive values in order to have correct y0 and y1 coordinates. then the data is drawn this way:

``````state.selectall("rect")
.data(function (d) { return d.values; })
.enter().append("rect")
.attr("width", x.rangeband())
.attr("y", function (d) { return y(d.y1); })
.attr("height", function (d) { return y(d.y0) - y(d.y1); })
.style("fill", function (d) { return color(d.name); });
``````

i have added stacked bar chart to my koextensions project https://github.com/hoonzis/koextensions you can check out directly the d3barchart method here: https://github.com/hoonzis/koextensions/blob/master/charting.js

cheers