DEV Community

Amber M Webb
Amber M Webb

Posted on

Create a D3 Bar Chart with Different Width Bars

Recently, I was asked to develop a bar chart in D3.js. No big deal, right? I have been writing D3 charts for about 6 months and have really enjoyed bringing data to life in applications for end users to consume. D3 has excellent documentation and even better examples that I have used to learn how to build these charts. The problem I ran into with this particular bar chart is the requirements were unlike the past charts. The bars would not be neatly and equally divided amongst the width of the chart and the x axis using scaleBand() function. These particular bars would have varying widths and the total of the bars would equal the max value of the x axis.

I couldn't find any examples that made sense for me, so I tried some things on my own. I used a linear scale for the x axis and set the width of each bar, but the bars were overlapping. After some deep thought and Google-fu, I came across a StackOverflow post that helped get past my mind block. I have to calculate the x attribute of each bar! Aha!

Instead of a lengthy explanation of how and why this works, here is my code example of a bar chart with bars of varying widths https://github.com/amberwebb/d3-charts/blob/master/src/BarChart/index.js

Pay attention to the x attribute. This function takes all of the values (starting from 0) and calculates the x value of each bar. The bars retain their own widths, no overlapping and the total of the bars equals the max value of the x axis. Requirements met!

Alt Text

Top comments (0)