d3.js堆积条形图与正值和负值

问题描述:

我是新的d3.js,并试图构建一个堆积的条形图,其中将沿x轴每个刻度的正值和负值,但我似乎不知道如何去。我尝试在 http://bl.ocks.org/mbostock/1134768 修改示例没有效果。

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.

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

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

这是排列数据的方式。我假设变量d保存给定x坐标的每个项目的值。数据收集是一系列值,如:

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
}

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

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

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

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

干杯