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!

Members only
4 minutes read

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:

schema explaining what the scaleBand() function produces

All the numbers produced by the scaleBand() function.

You can easily compute these values using the scaleBand() function!

  • The domain is an array that lists the groups.
  • The range is a two-element array that specifies the pixel positions where the shapes will be drawn.
  • The optional padding method 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()); // 60

That'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! πŸ™