Search⌘ K

Custom Bisectors

Explore how to create custom bisector functions in D3.js for comparing date values within datasets. This lesson guides you through defining a bisector with an accessor function, correctly locating data points, and updating visual elements interactively. By learning this, you will be able to refine tooltips and other UI features in your data visualizations effectively.

We'll cover the following...

We are going to create a custom bisector function. D3 comes with a bisect() function, but it is only capable of comparing numbers. We need to compare dates. Luckily, D3 comes with a function for creating a custom bisector for searching through an array with non-numeric values. We’re going to continue working on the event handler function.

Creating a custom bisector

Inside the function, we are going to replace the index variable.

Javascript (babel-node)
// Tooltip
ctr.append("rect")
.style('opacity', 0)
.attr("width", dimensions.ctrWidth)
.attr("height", dimensions.ctrHeight)
.on('touchmove mousemove', function(event) {
const mousePos = d3.pointer(event, this)
const date = xScale.invert(mousePos[0])
// Custom Bisector - left, center, right
const weatherBisect = d3.bisector(xAccessor).left
const index = weatherBisect(dataset, date)
const weather = dataset[index - 1]
console.log(weather)
})
.on('mouseleave', function(event) {
})

It is being set too early because we do not have the custom bisector function defined. We have a variable called weatherBisect. Its value will be the d3.bisector() function.

The bisector() function will allow us to create a custom bisect function. The reason we will create a custom bisector function is because we need to tell D3 how to access the date in our dataset. This function has one argument, which is an accessor function. We are providing it with the ...