Felix
Felix

Reputation: 619

D3's scale not working properly

Well, I'm starting with D3 and I'm trying to create a vertical bar chart.

I really don't know what's happening but some things are not working as expected for me (maybe because I'm just a noob on the matter).

I'm using line scales, works pretty well with axes, but it's miscalculating the height of the bars, for instance the higher values are not displayed (because of the low value of the result).

I've used the d3.max to determine the range. I really don't get what's happening.

var yScaleLeft = d3.scale.linear()
    .domain([0, d3.max(stats)])
    .range([realHeight, 0]);

.attr("height", function(d) {
    return yScaleLeft(d);
});

Here is the code: http://jsfiddle.net/aKhhb/ Look at * Scales * and // Stats bars

(Just forget about the x-alignement of the bars, I will see that later, I want to set its height properly)

Thanks a lot! Y saludos desde Chile :)

Upvotes: 3

Views: 3040

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

The issue is that your input and output ranges are mirrored -- that is, the largest input value maps to the smallest output value. That is fine, but you need to take it into account when calculating the y and height attributes. Essentially, you had the calculations for both reversed.

Fixed fiddle here. I've also fixed the x axis by adding your margin and half of the bar width to the computed x positions. Oh and you don't need parseInt() when doing calculations, only when you actually want to parse an integer from a string.

Upvotes: 1

Related Questions