Writing Scales
Explore how to write linear scales in D3.js for transforming data values into visual dimensions. Learn to set input domains and output ranges dynamically using d3.min, d3.max, and d3.extent functions. This lesson equips you to scale your data correctly for accurate and scalable scatter plot visualizations.
We'll cover the following...
In this lesson, we are going to learn how to write a scale. If you are working locally, you should set up a separate project for this example. Let’s say we had the following:
const slices = [100, 200, 300, 400, 500]
We have an array called slices. The array is based on the example we talked about in the previous lesson. We want to convert this data into something that can be drawn onto the screen.
Defining a scale
We are going to create a scale. First, we need to store a scale in a variable. Scales are generated by D3. They are not ready to go out of the box. We need to instruct D3 to prepare a scale. Each scale is tailored to our needs. Since it’s unique, we should store it for future use.
We will declare a variable called scale. It will be assigned to a function called d3.scaleLinear().
There are various scales available, but the linear scale is the simplest one. We are going to start by learning this scale. If we were to run the above example, we would find the following in the console:
The scale variable is a function. The function returned can transform our data. Let’s try ...