Other scale types
While scaleLinear is one of the most commonly used D3 scales, other scale types are essential for creating even basic charts.
Let's explore scaleBand, scaleOrdinal, and other indispensable functions!
scaleBand() to create... bands
scaleBand() is ideal for categorical variables as it allocates equal space for each category, ensuring that every discrete value is uniformly represented on the axis.
Example
You want to create a horizontal bar chart with 3 bars in a figure that is 240 pixels high. You want to dedicate 33% of the total height for white space: this is the padding between bars.
You'll end up with the dimensions outlined below:

All the numbers produced by the scaleBand() function.
You can easily compute these values using the scaleBand() function!
There are many ways to control the padding. The official doc explains very well!
- The
domainis an array that lists the groups. - The
rangeis a two-element array that specifies the pixel positions where the shapes will be drawn. - The optional
paddingmethod is expressed as a fraction of the band width.
const yScale = d3.scaleBand()
.domain(['A', 'B', 'C'])
.range([0, height])
.padding(0.1)Now that this scale is available, let's use it to get all the positions we need! Note that the yScale function we now have returns the start of the corresponding band:
// Top of each bar:
console.log(yScale('A')); // 0
console.log(yScale('B')); // 90
console.log(yScale('C')); // 180
// Width of a bar:
console.log(yScale.bandwidth()); // 60That's it! We have all the numbers we need to make a barplot!
Oh no! π±
This lesson isnβt available just yet.
Take a look at the status badges next to each lesson in the sidebar to see when itβs coming out.
Thanks for your patience! π