D3 Bar Chart - How to Calculate Bar Height?

Hello everyone, I am hoping someone can help me with some math, because that is my weakness! I am working on the bar chart project, my first attempt at data visualization.

I have two linear scales for axes and the x and y coordinates of the bars. But the data is so large making the bar height go off the bottom of the chart. So I figured I needed a number to scale the heights of all the bars. But how do I calculate that number? By eye I have figured out 1/69.5 looks about right. Anything smaller and the bars don’t go down to the bottom axis. Anything larger and the bars are too long. But I don’t want to just hard-code it.

Maybe I am going about this all wrong. Or maybe I am using the linear scales incorrectly. Any guidance in the right direction would be very helpful!

Here is my code: https://codepen.io/stressstressstress/pen/VwYVvNj?editors=0010

Hello stress^3.

Do not ask my exact workflow for this, as it was just my taking variables and adjusting for changing parameters, with minimal thinking.

const barScale = (h-(paddingBottom+paddingTop))/data[data.length-1][1];

Place that after your data definition. It adjusts for changes in canvas height, which is what I struggled with most.

There is a good chance the equation is missing some small parameter, but I am unable to justify adding any constant.

Hope this helps

Nice! Thanks so much! This makes sense to me.

It’s essentially: (max height a bar can have) / (max data value)

So when used to scale the heights, the bar for the max data value will have the max height.

Just because the last element in the array isn’t necessarily the largest, would it be better to use d3.max() instead?
const barScale = (h-(paddingBottom+paddingTop))/d3.max(data, d=>d[1]);

Yes, you are quite right. I was so focused on the specific data you had.

1 Like