Contents

Use min, max, extend and map functions in D3.js

Contents

It could be very boring to add multiple values in a dataset in D3.js because we need to update scales, axis and shapes. This is not a big issue when you have just one value to add but if you have thousand of value to add in your dataset, you need to do it automatically.

In D3.js you can update scales and axis regarding to the maximum and the minimum of your data. Therefore, you could have an axis that always take the maximum in your data.

I will show you how it works, it’s pretty simple. First, let’s define a dataset:

1
2
3
4
5
6
7
8
const data = [
	{ name: "alpha", value: 43543 },
	{ name: "beta", value: 79456 }, 
	{ name: "charlie", value: 12345 },
	{ name: "delta", value: 65421 }, 
	{ name: "echo", value: 35796 },
	{ name: "fox", value: 95148 }
]

Now, this is how we can get the minimum value in the dataset:

1
2
const min = d3.min(data, d=>d.value)
console.log(min) //12345

Here the syntax of the max function

1
2
const max = d3.max(data, d=>d.value)
console.log(max) //95148

The max and min method are very simple to use, you can just add them in the definition of your scale like this: see:https://www.datackling.com/post/how-to-manage-linear-scales-in-d3-js

1
2
3
4
const Yscale = d3.scaleLinear()
	.domain([min, max])
	.range([0, 500])

Instead of using both max and min in the definition of the domain for your scale, you can use the extend method. It will give you a list of two values: the min and the max of your data.

1
2
const extent = d3.extent(data, d => d.value)
console.log(extent) // [12345, 95148]

As I said, you can use the extent method in the definition of the domain of your scales. Finally, I want to show you the map method. This will return the list of attributes from your data. For instance, imagine that we have thousand of names in the data above, with the map method we can get all the names in just one line. Let me show you:

1
2
const names = data.map( d => d.name) 
console.log(names) // ["alpha", "beta", "charlie", ... ]

These methods are very useful to update your chart in a more automatic way. I hope you enjoyed this post. Do not hesitate to ask your questions in DM.

See you!