Welcome to d3aday! If this is your first time, we recommend reading the about page before jumping in.
Unlike most of the exercises thus far, the focus of this exercise is not on binding data to objects or drawing data to the screen, but on an enhancement to the presentation - the tooltip. Tooltips allow you to keep your chart uncluttered but still provide detailed information when and where it’s needed.
The Inspiration
The inspiration for this exercise comes from the always-entertaining Google Trends. We have created a viz in Trends that compares results for 2 Google searches over time - “dji drone” and “fpv drone”.
In this viz, the trend lines clearly stand out, but the actual numbers take a back seat. Until you roll over the graph. A nice tooltip pops up and gives you precise metrics for the spot where you’re hovering, allowing you to interact and drill down without getting overloaded.
Of particular note is the formatting of the tooltip information - clear distinctions between the date range and the underlying data, and color coding to visually match the data points to their trend lines.
The Exercise
For our version of this viz, we’ve simplified it a little. The Trends interaction has a sliding vertical line and data points that appear on rollover, but we’re focusing just on the tooltip window itself.
There are many good examples of D3 tooltips online, particularly Bostock’s example here. Even the “simple” ones, though, tend to be complex, and if you’ve never created one of these before I encourage you to keep it as simple as possible. For example, you may want to create the basic structure of the tooltip in HTML, rather than building it dynamically.
Then you can add and modify the elements with D3 as needed. If you can, try to incorporate the color and layout elements of the Trends tooltip.
If you’re following along with the inspiration graph, the data can be downloaded from the Google Trends page. For convenience I’ve placed it in this gist as well.
For a head start, you can use the code below to lay the groundwork with everything but the tooltip.
A Solution
My solution looks like this:
The tooltip implementation code is below. One nice trick that this incorporates is the use of the D3 bisector function generator to help map the mouse position to the data. Several online tooltip examples use it like so:
Get the mouse X position
Use x.invert to convert the position to a date
Use bisector to find the spot in the sorted data array where this date would fall
Further refine the selection by finding the array element that’s mathematically closest to the date
Given the close packing of the data in this solution, the last step isn’t really necessary and has been removed to keep it simpler.
The solution code is below, but as always you’re encouraged to try writing it yourself before peeking. The complete code (with HTML and CSS) is available on codepen.