Introduction to scales
Building a graph requires to transform a dimension (a numeric variable in your dataset) in a position in pixels. This is done using a fundamental dataviz concept called scale.
Before implementing it in the next lesson, let's describe a bit what this crucial concept of dataviz is.
Test your intuition
Let's test your intuition with the following exercise.
- 1️⃣ You have a SVG area with a width of
500px
. - 2️⃣ You can place circles anywhere along this area horizontally.
- 3️⃣ 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 = 410px
The 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.