My Favorite Tooltip Method for a Line Graph
Learn how to project a circle on the point where the tooltip will appear on your line graph.
We'll cover the following
Purpose
Tooltips are a fabulous way to include an interactive element on a graph and a great mechanism for including additional focused information to the user.
There are quite a number of different ways to implement tooltips (one of which you can find in the “Adding tooltips” section of the “Assorted Tips and Tricks” chapter of D3 Tips and Tricks), and I would be very hesitant about proclaiming anyone better than another. However, the one we will work through here is my favorite when using a line graph, as I think it brings a “fuzzier” mechanism for deciding when a tooltip is highlighted (you don’t have to be over an object to get information on it), which I like.
The idea of this technique is to set an area the size of the graph that will be used to determine when a tooltip will be displayed. When the mouse enters that area, the display
style allows elements to be shown or hidden. This then tells the script to show the tooltip, and the location of the mouse determines which point will have the tooltip. In the example below, we can see that the mouse cursor is some distance away from the point that is being highlighted, but it is in line (in the vertical axis) with the highlighted point. In fact, we will use some clever maths to determine which date point (or point on the x-axis) is the one that will be used to generate the tooltip.
Get hands-on with 1400+ tech skills courses.