Introduction to scales
Building a graph requires transforming a dimension (a numeric variable in your dataset) into a position in pixels. This is done using a fundamental dataviz concept called scale.
Before implementing it in the next lesson, let's explore what this crucial concept is all about.
Test your intuition
Let's test your intuition with the following exercise.
- You have an SVG area with a width of
500px. - You can place circles anywhere along this area horizontally.
- You have a dataset with 5 values:
0,50,60,82,100
→ How do you position your circles to represent this dataset? Drag the circles below following your intuition:
Note: the number in each circle represents its value in the dataset.
How it actually works
The obvious part:
→ For a value of 0, the circle should be placed at the extreme left of the SVG. This corresponds to cx = 0px.
→ For the highest value in the dataset, 100, the circle should be positioned at the extreme right of the SVG. This corresponds to cx = width (i.e., 500px).
→ For a value of 50, which is the midpoint of our dataset, the circle should be positioned at the center of the SVG. This corresponds to cx = width / 2 (i.e., 250px).
The math part:
For a value of 82, which is not an exact midpoint, you need to calculate the position proportionally.
The position can be calculated as:
// Linear scale equation
cx = (value / maxValue) * width
// cx = (82 / 100) * 500
// cx = 410pxThe Great News
Manually calculating positions for each data point would be incredibly tedious for every graph you create.
Fortunately, d3.js provides a function called scaleLinear() that handles this task for you. In the next lesson, we'll explore how it works and simplifies your data visualization process.