Creating Bins

The ‘d3.bin()’ function will help us with formatting our data into distributed buckets.

Let’s use the d3.bin() function to help us create bins. It is going to help us format our data. Let’s pick up where we left off.

The d3.bin() function

We will write the code for the bins below the xScale variable in the script section.

Press + to interact
// Create Scale
const xScale = d3.scaleLinear()
.domain(d3.extent(dataset, xAccessor))
.range([0, dimensions.ctrWidth])
.nice()
const bin = d3.bin()
.domain(xScale.domain())
.value(xAccessor)
.thresholds(10)

We have a variable called bin. Its value is the d3.bin() function. The d3.bin() function will return a function that can format data. This allows us to reuse the function for more than one dataset. Before we pass our data onto the bin() function, it will need to know more information about our data. First, it needs to know the domain by chaining the domain() function.

The bin() function needs to know the smallest and largest values in our dataset AKA the domain. We already provided the domain to the xScale function so we can pass in the same code we passed into the domain() function of the xScale function. However, there is an alternative solution available. We can access the original scale via the domain() function.

The xScale function does not have to be used as a function. It is also an object where we can grab information about the current scale. Rather than recalculating the domain, we can call the domain() ...

Access this course and 1400+ top-rated courses and projects.