We last left off at a basic bar chart written in d3v4. The x-axis tells us what CAUSE the bar is associated with. Each bar’s height tells us the number of deaths from that CAUSE.
Tooltips are a nice way to enhance the user experience, and provide more detail than is immediately visible. We added tooltips that activate on mouse hover (or screen touch) which tell us the exact number of deaths that a bar represents.
This chart has already come a long way toward providing us information, so any changes we make to it from now will be done with the aim of extracting as much information from the chart as possible.
To this end, the chart suffers from a usability issue. The smallest bars on the chart are difficult to aim the mouse over. You have to be fairly precise to see the number of MEASLES related deaths, for example.
A few best practices have evolved over the years. One thing many d3 programmers will do is to add invisible <rect>
s on top of the existing bars. These invisible elements are made to be full height and full width, so that hovering the mouse on a bar (or in the empty space above it) will fire off the mouse over event and show the tooltip.
This means that the data is joined to two sets of <rect>
s: one for the actual bars in the chart, and the second set to capture the mouseover event and show a tooltip.
We use an alternate method to maximize the hoverable area for each bar. We’ll use one set of bars – these become the bars in the bar chart. We’ll also make use of SVG:defs
, which are used to create/store reusable elements for your SVG.
For our bar chart, we’ll define and store linearGradients in the defs
section.
<rect>
) per datum<rect>
s and once to the linearGradients
in <defs>
).linearGradient
s don’t support mouse interactions directly, so changing the bar color dynamically involves an extra lookup step.