Linear Scales


The previous lesson described the concept of scale in data visualization. Scales allow, for instance, to translate a value in our dataset to a position on the screen.

Now, let's study the most common scale type and its d3.js implementation: the linear scale and its scaleLinear() function.

Free
4 minutes read
05060821000 px250 px500 px

The scaleLinear() function

The scaleLinear() function is part of the d3-scale module of d3.js.

It expects 2 inputs: a domain and a range.

🏠 Domain

Usually an array of length 2. It provides the min and the max of the values we have in the dataset.

📏 Range

Usually an array of length 2. It provides the start and the end of the positions we are targeting in pixel.


The output is a function that takes a single argument. You provide a value from the domain, and it returns the corresponding value from the range.

Let's create a scale to address the issue with the green circles above!


import {scaleLinear} from d3

const scale = scaleLinear()
  .domain([0, 100])
  .range([0, 500]);

console.log( scale(82) )
// 410

      

Dealing with the Y Axis

By now, working with the X scale should feel intuitive.

However, the Y axis behaves a bit differently. Typically, when a value is high, we expect the corresponding data point to be near the top of the SVG area. Conversely, a value close to 0 should appear near the bottom.

This means the Y scale is essentially inverted! Luckily, we can handle this easily by reversing the order of the range array.

Take a close look at the code below:


const yScale = d3.scaleLinear()
  .domain([0, 100])
  .range([300, 0]); // Array is inverted! Smallest value will return 300px = bottom of the svg area

console.log(yScale(0))    // 300
console.log(yScale(100))  // 0

Exercices

Wouch! 😅

That was challenging!

Scales are a core concept in D3.js data visualization, which is why we needed so many exercises!

You've mastered the most important part, but we're not done with scales just yet. Let's explore a few other useful scale types!