javascript - D3 make stacked bar chart dynamic -
i trying follow example: http://bl.ocks.org/mbostock/3886208

in application have show stacked bar chart can see example how many different animals specific user bought.
here object:
[["personname1", 10, 10],["personname2", 4, 16]]; first property name, second animal type 1, , third animal type 2.
i've got stuck in foreach loop:
data.foreach(function(d) { var y0 = 0; d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; }); d.total = d.ages[d.ages.length - 1].y1; }); what code lines below do?
d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; }); i can't figure out how same thing objects.
i've tried this:
scope.data.foreach(function(d) { var y0 = 0; d.animals = color.domain().map(function(name) { return {name: d[0], y0: y0, y1: y0 += +d[1]}; }); d.total = d.animals[d.animals.length - 1].y1; }); but d.animals empty.
and have use later on in:
state.selectall("rect") .data(function(d) { return d.animals; }) .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); }); any ideas?
that particular bit of code rather confusing way of converting values in row array of cumulative values. depends on previous line of code, domain of color scale defined keys first data object (i.e., column names in csv file) except "state". maps array of column names array of objects, each of contains column name, total of previous values (y0), , new total created adding corresponding data value (extracted data-row object data[name]) old total. in addition being assigned y1 property of object in ages array, new total assigned y0 variable carries on mapping next value in array.
this wasn't working you, because data rows represented arrays, not key:value objects created reading csv file. aren't able create array of column names, , aren't able use names access data. you'll have create sub-arrays yourself, using array index numbers access different data values.
if that's still confusing, recommend @ this or this example, both use d3 stack layout object calculate top , bottom positions of stacked bars.
regardless of how calculation, end goal create sub-array each of data rows, containing objects each of values want stack. each object needs have y0 value representing total of previous values in stack (i.e., bottom of bar), , y1 value representing total of bar , previous ones (i.e., top of bar).
you save height of bar instead of 1 of these values, stack layout creates y0/y1 structure, since easy use stacked area graphs. area defined position of lines, not height.
Comments
Post a Comment