Bar chart - cut off below 0

Hi all,

I’m working on the bar chart project, and i have it 100% passing, but I don’t want to leave it as is.

Problem: the bars are drawing, and showing below the x-axis

Here is my codepen:

Is there a way to fix this? Am i calulating height wrong (it looks right as per the example project given)?

You set your x-axis position with

   svg.append('g')
      .attr('transform', 'translate(0,' + (height - padding) + ')')

which moves it padding up from the bottom of the svg canvas. You need to similarly adjust the height of the bars from (yours, slightly modified)

      .attr('height', (d) => {
        return d[1];
      })

so that the height is just to the axis as above by scaling the GDP value with your yScale (where the bar should start, like you have for the y coordinates) to the axis (height - padding). This code returns the value of the GDP, which compared to the scale of the graph is large enough to cause all the rectangles to extend past the lower edge of the SVG canvas.

It’s interesting that this situation wasn’t tested in the project. Once you work it out you should check into filing an issue and possibly writing a test to detect this since you discovered it.

so i changed it to

.attr('height', (d) => { return yScale(d[1]) })

and i get :


and causes test to fail

Am i misunderstanding you? Or is there something wrong with my yScale? Padding inside or out of that yScale has no ‘visible’ difference

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

Somewhat. D3 coordinates are measured from the top left corner of the canvas, with positive values being right and down. You need bars that stretch from the value of the GDP on the graph (yScale(d[1]) usually in your code) to the x-axis located at height - padding. This new code

will return the distance from the top of the canvas, and use that for the height of the bar, measured down from the top of the bar, which means the bars get shorter as the GDP increases because they start closer to the top.

Your original yScale() was working correctly. It should have a maximum range of height - padding since that is where the axis is and a minimum of 0 (the top). Then if you subtract the maximum (height - padding) and the start of the bar (yScale(d[1])), you should get the height of the bar you need (measured down from the top of the bar).

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