Contents

How to Manage Band Scales in D3.js?

Contents

In this article, I will show you when we need band scales and how to use them.

Band scales are useful when you need to add a value to a bar chart and you don’t want to adjust the width of the SVG. Band scales allow to fit the data to the SVG width automatically and responsively. You could define the padding between each bar and between the outer bar and the side of the SVG canvas. Band scales take discrete values in input domain and return continuous values.

How to define a band scales? First let’s use the scaleBand() method:

const mybandscale = d3.scaleBand()

Then, we add the input domain:

mybandscale.domain(["France","England", "Italy", "Spain","Germany"])

Now, we define the range of the output domain:

mybandscale.range([0, 400])

Finally, we precise the inner and outer padding:

mybandscale.paddingInner(0.2).paddingOuter(0.3) Perfect! Now you could (and you should) use band scales to display your bar charts as they allow you to easily add value in the input domain and to display it responsively.

That’s it for this post, I hope you enjoyed it. Do not hesitate to ask your questions if it’s not clear or if you get stuck.

See you!