Search⌘ K
AI Features

Understanding Bisectors

Understand how to use bisectors in D3.js to dynamically locate the right position for tooltips on line charts. This lesson guides you through converting mouse coordinates back to data values, using scales and the bisect method to find corresponding data points, improving interactive chart accuracy.

We'll cover the following...

We are going to need to figure out where to display the tooltip. At the moment, we know where the reader is hovering their mouse. However, we do not know where to display the tooltip. We do not even know which point the reader wants to view. The only information we have at our disposal is the x and y-coordinates of the mouse.

We are going to use a bisector to help us figure out where to display the tooltip. A bisector is a function that allows us to locate where to insert an element into an array in order to maintain a sorted array. Before we discuss how a bisector will help us, let’s look at an example of how a bisector works.

Bisector example

Let’s say we had an array of five numbers. The numbers in this array range from 10 to 50.

Javascript (babel-node)
const numbers = [10, 20, 30, 40, 50]
numbers.push(35)
// New Array: 10, 20, 30, 40, 50, 35

We may want to push a new number into the array. For example, we may want to push the number 35 into the array. One solution would be to call the push() function. The number would get inserted onto the end of the array. JavaScript will create a new array with our number inserted ...