LE-HU
LE-HU

Reputation: 881

D3.js bar graph scale/range problem. Bar graph too low

I've completed a bar graph codepen showing US GDP (the popular one from FCC).
https://codepen.io/le-hu/pen/Baoywgd

The problem i can't eradicate is such - the graph does not start at bottom padding 50units above svg bottom, but instead spans to the border and even goes below svg border i believe. I've tried changing every setting. My bet is something's wrong with the yScale domain, or range property.

  const yScale = d3.scaleLinear()
                   .domain([0,
                     d3.max(data.data, d => d[1])])
                   .range([height - padding, padding]);

Code seams to be ignoring the height - padding part in range setting. (or my understanding of it)

I'd like the graph to start on the line the x axis we have, the one showing dates in years 1950+.

Just like in the original:
https://codepen.io/freeCodeCamp/pen/GrZVaM

thank you for any insight!

Mehdi's solution worked like a charm - thank you very much for your time!

Upvotes: 0

Views: 403

Answers (1)

Mehdi
Mehdi

Reputation: 7403

In SVG, the vertical coordinates go from top to bottom(reference).

This makes the reasoning about the y coordinate and height of a vertical bar in a bar chart less straightforward.

The tutorial Let's make a bar chart, part 4 explains how to perform this.

the y position of the rectangle has correctly been set tothe one of the value d[1]:

.attr("y", (d, i) => yScale(d[1]))

The height of the rectangle is incorrect, though. It should be the distance between origin (value 0) and position of the value d[1]. As shown below:

.attr("height", (d, i) => yScale(0)- yScale(d[1]))

Upvotes: 2

Related Questions