4

I am new to d3.js and trying to build a stacked bar chart in which there would be positive and negative values for each tick along the x axis, but I cannot seem to figure out how to go about it. I was attempting to modify the example at http://bl.ocks.org/mbostock/1134768 to no avail.

4

1 回答 1

4

我遇到了同样的问题。毕竟我带来了以下解决方案:

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);
});

这是排列数据的方式。我想变量 d 保存给定 x 坐标的每个项目的值。数据集合是一个值列表,例如:

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

要显示的项目的名称必须映射到域,然后每个月我们必须汇总数据。对于给定月份的每个项目,我都有一个 y0 和 y1 坐标。为了获得正确的 y0 和 y1 坐标,我们必须有单独的负值和正值计数器。然后数据是这样绘制的:

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); });

我已将堆叠条形图添加到我的 KoExtensions 项目https://github.com/hoonzis/KoExtensions您可以在此处直接查看 d3barChart 方法:https ://github.com/hoonzis/KoExtensions/blob/master/charting.js

干杯

于 2014-01-10T15:02:08.473 回答