functionoid - 6 months ago 8x
Javascript Question

# D3.js stacked bar chart

I've spent enough time modifying the stacked bar chart sample that it would be wise to get a second pair of eyes to look at what I'm doing wrong. The modified sample is in a js fiddle.

My main changes are these:

1: On line 10 reversed the array for range

`y = d3.scale.linear().range([height, 0])`

2: On lines 17 and 22 added axis

``````var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(format);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
``````

3: Line 62 changed the addition of y0 and y (this is the change that might be creating problem)

``````.attr("y", function (d) { return y(d.y) - y(d.y0); })
``````

As you can see bars are going way above the specified height.

If someone could tell me what I'm doing wrong I'd be very thankful. I spent too much time looking just by myself. I do think I'm very close as chart is displaying other than the height problem.

There is one more change, which you haven't mentioned: that you the chart containing `g` is now translated to the top-left point instead of the bottom-left point, as was in the original plot.

Changing the following two lines around the line you mentioned will solve the problem:

``````            .attr("y", function (d) { return y(d.y + d.y0); })
.attr("height", function (d) { return y(d.y0) - y(d.y +d.y0); })
``````

Demo

This is how I generally do these calculations with an inverted scale such as `y = d3.scale.linear().range([height, 0])`:

Here, the point `S(y + y0)` will be the value of the point closer to the `top`, or with the lower `y` value, and the `height` of the bar will be = `S(y0) - S(y + y0)` or = `abs(S(y0+y) - S(y0))`, whichever you find more palatable.

However, to be honest, there is plenty of trial and error involved before I actually draw this down. Then I do more trial and error to find the solution and convince myself that this drawing helped.

So ... your mileage might vary. :)

Source (Stackoverflow)