Search⌘ K
AI Features

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, ...

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 ...