Contents

How to Manage Logarithmic Scales in D3.js?

Hello! In this post I will show you why logarithmic scales can be interesting in D3 and how to manage them.

1. Why use logarithmic scales instead of linear scales?

Sometimes in your data, there is a lot of variation between the biggest values and the smallest. It could be very difficult to display the whole values in one chart and keep it readable.

Logarithmic scales allow you to deal with this issue. In linear scales, each unit increase (or decrease) in a linear way, always with the same value. Usually in logarithmic scales, each unit increase with a ten’s power. In this way, you reduce the distance between the low values and the large value in your chart.

2. How to implement a logarithmic scale in D3.js?

If you have already use linear scales, logarithmic scales will be very easy to understand and to implement in D3 for you (see: https://www.datackling.com/post/how-to-manage-linear-scales-in-d3-js ).

First, we use the scaleLog() method to define the scale:

const logscale = d3.scaleLog()

Then we add the input domain:

logscale.domain([300, 150000])

Now, we define the range:

logscale.range([0, 400])

Finally, we precise the base (here 10):

logscale.base(10)

To summarize, here is the code that allows you to display a bar chart using a logarithmic scale:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 logscale = d3.scaleLog()
		.domain([300,150000])
		.range([0,400])
		.base(10)

	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 => logscale[d.height])
		.attr("fill", "green")
})

Here we suppose that we have a csv file that contains data with a large difference between small values and big values.

That’s it! As you can see, it is very similar to linear scale and if you know how to define a linear scale you already know how to define a logarithmic scale.

I hope you enjoyed this post and do not hesitate to ask your questions in DM.

See you!