D3 graph is backwards?

I’m doing the first project for the data visualization course, but I’m stuck in trying to get the API data to display properly. For some reason, the values on the left are displaying taller than the values on the right, even though they’re smaller.

I figured I must’ve inversed something somewhere, but I can’t find it.

(Also I’m not sure why the bars don’t line up with the bottom scale, but that’s - maybe - another issue…)

They are the same issue, and it’s all here:

``````    const yScale = d3.scaleLinear()
.domain([0, 20000])

svg.selectAll("rect")
...
.attr("y", d => h - yScale(d[1]))
...
.attr("height", d => yScale(d[1]))
...
``````

You just have to remember that D3 uses the top-left as the origin for its coordinates, which means that the y coordinate always requires more work. Your scale is correct since it maps 0 to 20,000 onto the y coordinate of the x-axis (`h - padding`) and the top of the graph (`padding`). The “y” `attr` needs to be the top of the `rect` you’re drawing, which is between 0 and 20,000 and should be the value from your scale without further modification since your scale is already mapping 0 to 20,000 to the graph’s range. The “height” `attr` needs to be the distance this rect will span downward from the “y” `attr`. Since you want the `rect` to intersect the x-axis, you need to find the difference between the x-axis “y” `attr` and the “y” `attr` of the `rect`.

Your current code is almost correct, but if you assume the first `rect` has a value of 100, your scale maps [0, 20000] to [450, 50] (`h = 500`, `padding = 50`), which comes out to about 448. If the “y” `attr` is `h - yScale()`, then that evaluates to 52 (near the top of the graph, not the bottom), which makes the “height” 448, which is the bottom (52 + 448 = 500). So for small GDP values, you get huge bars that cover the whole graph. You really want the `rect` to start at 448, and have a height of 2 so that it can intersect the x-axis at 450.

Or, in short, your `yScale` includes padding, and not just the range of the graph.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.