Contents

How to Manage Linear Scales in D3.js?

Scales are important features in D3 if you don't want to get stuck when you have big numbers in your data.

1. What are scales?

Scales are functions that map from an input domain to an output range. Today we will talk about linear scales, the simplest scales in D3.

2. How to implement linear scales in D3.js?

We use the scaleLinear() method to define a linear scale.

const scale = d3.scaleLinear()

As I said in introduction, scales are functions taking an input domain parameter. Let’s define it.

We assume that we have “big numbers” in our data and that we would like to display a bar chart regarding this data.

scale.domain([0,4500]); //definition of an input domain

Now, we suppose that we have an svg canvas with a height of 500 pixels and that we can’t exceed this value. Let’s define an output range.

scale.range([0, 500]);

That’s it! We have a linear scale, so now we can display a bar chart using this scale regardless of the length of the bar. The magic of D3 will convert all input value in the input domain into an output value from the range.

Let me show you the full code for this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const svg = d3.select("#canvas").apend("svg")
	.attr("width", 600)
	.attr("height", 500)

d3.csv("mydata.csv").then(data => { 
	data.forEach(d => {
		d.height = Number(d.height)
	})
	const scale = d3.scaleLinear()
		.domain([0,4500])
		.range([0,500])

	const rects = svg.selectAll("rect").data(data)

	rects.enter().append("rect")
		.attr("y",0)
		.attr("x", (d,i => (i*60)))
		.attr("width", 40)
		.attr("height", d => scale[d.height])
		.attr("fill", "green")
})

I hope this post helped you to better understand linear scales and do not hesitate to ask your questions in DM if you have.

See you!