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/howtomanagelinearscalesind3js ).
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:


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!