All examples By author By category About

seemantk

Bar Chart Using linearGradient

Visualizing causes of death in Zambia: III

From the 2015 Living Conditions Survey

Introduction

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.

Fundamentals

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.

Beyond the Fundamentals

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.

Analysis

Advantages of this Approach
  1. Single visible element (<rect>) per datum
  2. Full height/width rectangles makes the maths easier
  3. Mouse is easier to aim for tooltips!
  4. Easy to switch direction for linearGradients (bars can hang from the top)
  5. Easy to switch orientation for linearGradients (bars can be horizontal, left-to-right or right-to-left).
  6. Rectangle dimensions are decoupled from the fill, so the rectangle can be any size, and the gradient fill will still reflect the dataset.
Drawbacks of this Approach
  1. An extra scale (d3.linearScale) is required to convert the data to percentages.
  2. The dataset is still joined (once to the <rect>s and once to the linearGradients in <defs>).
  3. linearGradients don't support mouse interactions directly, so changing the bar color dynamically involves an extra lookup step.

Improvements