0

I'm trying to build a stacked bar chart in D3js. I have problems to set properly y and y0 attributes and draw the bars on their right positions. Probably I have a calculation mistake but I cannot find it. This is the link to the example code FIDDLE The scenario is:

  1. I group the data first by "period" and the periods are shown on xAxis
  2. Then I have grouping by "type" - MONTH and ENTRY which should be stacked bars in different colors.
  3. The sum "amount" for each type per each period is shown on yAxis.

I use nest function with 2 keys to structure the data. The problem appears when I draw the bars in the actual stacked bar chart. I'm not sure whether the problem is in the way I access the data (key and values) or in the way I set the attributes "y" and "height".

selection.selectAll("rect")
    .data(function (d) { return d.values; })
    .enter().append("rect")
    .attr("width", x.rangeBand())
    .attr("y", function (d) { return y(d.values); })
    .attr("height", function (d) { return y(d.y0) + y(d.values); })
    //.attr("height", function (d) { return y(d.y0) - y(d.values); })
    .style("fill", function (d) { return color(d.key); })

The obvious errors are that one of the bars is hidden behind another one. And the second bar is under the xAxis.

I'm beginner in d3js and I cannot find the solution. Can somebody help me?

4

1 回答 1

0

我可以看到一些事情:

  1. 看起来你把nest. 您应该只需要嵌套一个级别。
  2. 当您实际上希望最大值是堆栈的总数时,您正在计算的最大值将永远是堆栈中单个元素的最大值。
  3. 您正在创建的组元素 ( g) 似乎以“错误”的方式分组。您通常希望对每个堆栈的相同“位”进行分组。也就是说,您希望rect每个堆栈的第一个与其他 first 位于同一组中rect。然后每个堆栈中的第二个将与其他第二个分组,rect依此类推。这可能是由于第一点的嵌套错误。
  4. 你实际上需要计算valueOffset你的小提琴,但被注释掉了。该值用于设置构建堆栈时的相对位置。

为了提供帮助,我根据您所写的内容整理了似乎正确的内容。看看下面的片段。

    var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 400 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;
            
var color = d3.scale.category10();

var data = [
    {
      "period":201409,
      "type":"MONTH",
      "amount":85.0
    },
    {
      "period":201409,
      "type":"ENTRY",
      "amount":111.0
    },
    {
      "period":201410,
      "type":"MONTH",
      "amount":85.0
    },
    {
      "period":201410,
      "type":"ENTRY",
      "amount":55.0
    }   
];
    
var x = d3.scale.ordinal().rangeRoundBands([0, width], .1, 0);
var y = d3.scale.linear().range([height, 0]);


var xAxis = d3.svg.axis()
                .scale(x)
                .orient("bottom");

var yAxis = d3.svg.axis()
                .scale(y)
                .orient("left").ticks(10);

var svg = d3.select("#chart")
                .append("svg")
                .attr("width", width + margin.left + margin.right)
                .attr("height", height + margin.top + margin.bottom)
                .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
                
            data.forEach(function(d) {
                d["period"] = d["period"];
                d["amount"] = +d["amount"];
                d["type"] = d["type"];
            });

var nest = d3.nest()
                .key(function(d) { return d["type"];});

var dataByType = nest.entries(data);
//var max = d3.max(dataByGroup, function(d) { return d3.sum(d.values, function(e) { return e.values; }); })

            //console.log("dataByGroup", dataByGroup);  
var stack = d3.layout.stack()
                .values(function(d) { return d.values; })
                .x(function(d) { return d.period; })
                .y(function(d) { return d.amount; })
                .out(function(d, y0) { 
                  d.valueOffset = y0; 
                });
            
//data: key: group element, values: values in each group
stack(dataByType);
var yMax = d3.max(dataByType, function(type) { return d3.max(type.values, function(d) { return d.amount + d.valueOffset; }); });

color.domain(dataByType[0].values.map(function(d) { return d.type; }));
x.domain(dataByType[0].values.map(function(d) { return d.period; }));
y.domain([0, yMax]);
            
svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 3)
    .attr("dy", ".71em")
    .style("text-anchor", "end");

var selection = svg.selectAll(".group")
    .data(dataByType)
  .enter().append("g")
    .attr("class", "group");
    //.attr("transform", function(d) { return "translate(0," + y0(y0.domain()[0]) +  ")"; });

selection.selectAll("rect")
    .data(function (d) { return d.values; })
  .enter().append("rect")
    .attr("width", x.rangeBand())
    .attr("x", function(d) { return x(d.period); })
    .attr("y", function (d) { return y(d.amount + d.valueOffset); })
    .attr("height", function (d) { return y(d.valueOffset) - y(d.valueOffset + d.amount); })
    .style("fill", function (d) { return color(d.type); })
    .style("stroke", "grey");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="chart"></div>

上述片段的一些注释(与我的评论相符):

  1. 一个更简单的巢:

    var nest = d3.nest()
                 .key(function(d) { return d["type"];});
    

    这个比你之前的简单多了,不需要做rollup功能。当您想要聚合数据时,通常需要汇总,在这种情况下您不需要,这应该说明您的嵌套过于复杂。

  2. y轴最大值的计算:

    var yMax = d3.max(dataByType, function(type) { return d3.max(type.values, function(d) { return d.amount + d.valueOffset; }); });
    

    这将计算您的轴需要采用的最大值,使一切都很好。

  3. 如果您查看生成的 SVG,您会明白我对rect每个堆栈中的 s 分组的意思。我通常发现以这种方式分组更容易。我想没有“正确”的方式,但这通常最适合我。

  4. valueOffset中的计算stack

    d3.layout.stack()
             .values(function(d) { return d.values; })
             .x(function(d) { return d.period; })
             .y(function(d) { return d.amount; })
             .out(function(d, y0) { 
               d.valueOffset = y0; 
             });
    

    计算valueOffset用于将rect堆栈中的每个“移动”到相对于其他rects 的位置。你会看到它被使用了几次,计算最大值y、 each 的yattr 和 each的rectthe 。 heightrect

我没有解释我所做的每一个更改,但希望通过以上内容和代码段,您将能够解决差异并将其应用到您的确切用例中。

于 2014-10-15T09:07:47.280 回答