Using nested data to create small multiples

In my previous post I talked about strategies to dealing with lots of data. Small multiples is a particularly powerful approach as it does give you a lot of flexibility as you can make a chart for each category you have. It’s also useful in situations like comparisons over time or comparisons against a national trend.

This post is a technical explanation about how to create small multiples using d3js. This is the approach that I use and it isn’t the only one. There are also different ways to create small multiples using different libraries (e.g. with Plot).

One big SVG or multiple SVGs?

In previous small multiple charts we made, we used to use one SVG and split it up into different parts. This made it trickier to set the external margin for the whole SVG and the internal margins for the individual charts. Now I prefer making multiple SVGs and getting them to line up with each other with CSS. I prefer it this way because it makes responsiveness slightly easier as the SVGs just flow naturally. This does have disadvantages for example annotations are harder because they have be able to fit on one small chart.

Nesting data

To be able to take advantages of d3js looping feature we need to rearrange our data to fit the format we want, specifically we need to create some hierarchy in the data.

Let’s work through the example of figure 3 in the Deaths registered weekly bulletin which looks at the number of excess deaths by setting.

Number of excess deaths by place of occurrence, England and Wales, registered between 7 March 2020 and 27 August 2021

The data behind this chart would normally look something like this

Date Home Hospital Care home Other
Week 11 145 -303 -60 30
Week 12 286 -270 6 53
Week 13 427 341 264 -22

Although this is table is good to read as humans and is a small file size, it’s not quite the right format for creating nested data. We need something a bit more like this

Date Setting Value
Week 11 Home 145
Week 11 Hospital -303
Week 11 Care home -60
Week 11 Other 30

This format is known as long format or tidy format, where each data point has a single row and all the attributes about that data is in a column. This format also makes it easier when there are more attributes, for example if we had this excess deaths split by sex, we would have to either add extra columns (Home Male, Home Female) or duplicate tables with either merged cells or different tabs to differentiate between the two. In the tidy data format, we just add another column for sex.

Once we have data in this tidy or long format, we can nest it with d3.nest. With our example the code would look like

nested = d3.nest()
.key(function(d){return d.Setting})
.entries(graphic_data)

where graphic_data would be the data we’ve read in from the .csv.

Once we look at nested we find it’s been transformed into an array of 4 objects, one for each setting. Inside each object, there are the properties key and values. Inside values is a subset of the rows of the table that relate to the setting.

Gif showing nested data

Appending elements from nested data

Now we can use d3js to create our charts. We can use the standard .data().enter().append() pattern to first create our SVGs. Remember .data takes an array, .enter() is a selection for each new thing it needs to create that doesn’t already exist. Here we have 4 elements in the nested array, so it will create 4 SVGs.

svg = d3.select('#graphic')
.selectAll('svg.chart')
.data(nested)
.enter()
.append('svg')

The size of the SVGs is determined by the width of the page and how many charts you want on each row. I’ve omitted all the stuff to do with margins for brevity but what’s important to know is that all the charts have the same margin. The margin on the left of each chart is big enough for the ticks but also acts as a bit of breathing space between the charts.

When we want to create the bars for the chart, we can reference the data attached to each SVG. We know the data for the bars is inside the values property of each element of the nested array, so we bind that data to our rects.

chart = svg.selectAll('rect.bars')
.data(function(d){return d.values})//here d is the elements of the nested array so is attaching the array from the property values
.enter()
.append('rect')

You can now do data driven styling for your rects as each rectangle has the data bound to it.

When to call the axis generator

Here’s is the chart on mobile on the left and on desktop on the right.

Comparison of the chart on mobile compared to desktop

On mobile there is one chart per row and on desktop there are two charts per row. With exactly the same axis, you can easily compare the magnitude of different numbers but since the axis are exactly the same we don’t need to duplicate having axes on every chart, we just want the chart on the left side of each row to have the axis ticks. On mobile there’s only one chart in each row so you do need to have ticks on every chart.

To generate ticks only on the left axis, we can use d3’s each. This allows us to do something for each element individually. Here we are going through all the SVGs, using each to apply a function. The function looks at the index of the loop over all the selected elements and if the index divided by the number of charts per row is zero then we know it’s the left chart and we can call the axis generator with ticks, otherwise call the axis generator without ticks.

svg.append('g')
.attr('class', 'y axis')
.each(function(d, i) {
  if (i % config.chart_every[size] == 0) {
    d3.select(this)
      .call(yAxis.tickFormat(d3.format(",.0f")))
  }else{
    d3.select(this)
      .call(yAxis.tickFormat(""))
  }
})

You can also do something similar to just add the x axis label on the chart on the right.

Adapting this approach

If you’ve got categorical y-axis with long labels, it’s going to make the left margin very big would look very clumsy if you tried to repeat it for other charts. To get round this, I separated the left axis into a separate SVG and then did the nested data approach as above to create the small multiples for the final chart.

Custom left axis small multiple

In the above chart, the data is nested on two levels, firstly by sex, and then by how the model adjusted for various factors. When binding the data you can create an svg for each sex, when a g for each model, when inside you’ll have the data for the each ethnicity.

conceptual model for nesting two levels

Hopefully this helps you get your head round using nested data to create small multiple charts. For more information about binding data and creating things based on data I highly recommend Peter Cook’s guide to data joins and the enter exit update pattern.

Alternatives to plotting lots of data on a page

Imagine you’ve got some data with a lot of series and data points over time. You’ve tried a line chart but there is just too much data. You want it to look good but what are your options for visualising it?

Option 1: Just plot the series that matter

It’s more work but just reducing the number of series you plot leave you with just the most important data and a cleaner chart. This is easier to understand what’s going on at a glance. The hard part comes in choosing which series to plot.

From this

to this

Option 2: Use a heatmap

Although this will depend on your dataset and how many timeseries you have. One option to plot data with a time element is to use a heatmap with time running left to right as this is convention (in some societies). This is useful for showing general patterns as you won’t be able to show exact values with a colour scale.

Here are some examples

Option 3: Small multiples

Depending on whether what’s interesting is happening to individual series rather than between series another option would be to plot each series on a mini chart and have small but multiple version of the chart, one for each series. It would be hard to rely on colour alone to distinguish each series if all the series were on the same chart. What you do lose out on is resolution so this solution is better when you want to look at overall patterns rather than the detail. You’ll also want to keep the axis as similar as possible as you’ll be naturally comparing across charts so if they are different scales it makes it easier to misread the chart.

Option 4: Multiline

You could plot all the series on one chart, often in a neutral colour and use some way to highlight with a stronger colour a particular series of interest, for example through a dropdown

or hovering with the mouse

This puts the burden on the user to interact with the page to see what they are interested in or what is relevant to them. It also makes comparisons between series more difficult as you may have to select and remember.

All these solutions have positives and negatives to them and it comes down to what you are trying to say with your chart.

Tidydata Maker

The small multiple line chart template I developed last year uses tidy data but we are used to seeing data in a wide format as it makes it quicker to grasp what’s going on.

We have been copying and pasting data around to rearrange it to fit the format needed for the template and a colleague asked whether I could make something to do this quickly.

And here it is, the tidy data maker.

tidydatamaker

I wanted to learn svelte as part of building this tool and use their REPL tool. Here is the svelte code.

To publish the tool. I downloaded the zip file, unzipped it in a new repo and turned on Github pages. The only thing to note is that svelte put links to the root rather than local so once you’ve changed that so it looks like this it works.

<link rel='stylesheet' href='./global.css'>
<link rel='stylesheet' href='./build/bundle.css'>
<script defer src='./build/bundle.js'></script>

Since publishing this tool, many people have pointed out that this functionality exists in Excel as unpivot which is something I didn’t know.

Vector tiles resources

Tools

Vector inspector

Useful for checking the layer and field names

Mapbox tutorials

Interpolate opacity of layer based on zoom level

Joining data to layer using setFeatureState

Hover effect with feature state

Against all odds — how to visualise odds ratios to non-expert audiences

On Thursday 7 May, the ONS published analysis comparing deaths involving COVID-19 by ethnicity. There’s an excellent summary on twitter but the headline is that when taking into account age and other socio-demographic factors, such as deprivation, household composition, education, health and disability, there is higher risk for some ethnic groups of a COVID related death compared to those of white ethnicity. The full article goes into more detail including some of the caveats e.g. the strengths and weakness of using ethnicity data from the 2011 Census and not being able to use occupation.

How we presented odds ratios

What I’d like to do is talk a lot about the visuals we produced for the article.

First, what we are visualising is called an odds ratio. This definition comes from the ONS analysis.

An odds ratio is a measure of the relative risk of an outcome in one population compared with a different population, where odds ratios greater than one indicate the outcome is more likely while less than one is less likely.

It’s quite a hard concept to understand but we try out best to guide people with a number of features in the graphic.

Annotated image

1) We make it really clear that the odds ratio refers to a comparison group. This is in bold and with a thick line

2) We tell you what it means to be one side of the line rather than leave it to the numbers and knowing that a number higher than one is more likely.

3) We’ve plotted the odds ratio as a dot because we want it’s position relative to the comparison group to be noted. We’ve also plotted the confidence intervals as lines sticking out of the dot. These are again a statistical concept and may be confusing for people but they are useful for interpreting the chart. If the confidence intervals overlap with the line for the comparison group, it means we aren’t sure that the increase or decrease in risk is really happening in the current data. It may be there but we can’t tell at the moment. To be honest, we didn’t really explain this in the notes under the chart so there’s room for improvement.

4) We’ve changed the scales to factors of likelihood. We could have plotted the raw numbers but by using phrases it makes it more understandable.

What others did

This story was covered in other publications including the Guardian, BBC, FT(£) and Daily Mail. I’ve picked these out in particular because they’ve chosen to rechart the data in their own style. The Daily Mail is an interesting example as they redid the numbers in their own style and also included a screenshot of our charts.

The BBC

The BBC looked at the different models when we included different factors we could see how the odds ratio changed. This showed how much a factor was in reducing the risk. These charts are OK but the only thing I would pick up on was that they don’t plot the bars relative to the comparison group. It’s not stated but the bars appear to start from 0. An odds ratio of 0 means that the event is impossible.

This also causes an issue when they chart the risks for women.

BBCwomen

The Chinese ethnic group should actually be plotted as a bar between 0.8 and 1.

The Guardian

The Guardian do something similar, plotting bars from 0. They actually make a mistake when labelling the axis. They are plotting the odds ratio but label it as times more likely to die from COVID-19 compared to white. This would make the an odds ratio of 1 which is equal likelihood as the comparison group, one times more likely. You could use these axis but you’d have to take one off every value and you might struggle with odds ratios below 1.

Their second chart looks to display the different models on the same chart and allow a comparison between the two. We were thinking of doing something similar but it was felt that the confidence intervals were important to show here which would make it quite messy. Without the confidence interval you can’t tell if the different between the models is significant, which in 3 of the cases is not. This means that the difference between the models might be zero. It also doesn’t show the confidence intervals with relation to 1. The axis is also unclear as it isn’t said that the likelihood of 1 is equal to the comparison.

Financial Times

The FT also look to show the difference between the models. It’s not stated but this looks like for males. They have plotted bars from zero and use likelihood of dying without explaining that 1 is equal likelihood to comparison.

With all the bar charts, I feel plotting from zero is somewhat misleading as you might think since the bars have length at 1 this would represent an increase in likelihood but are in fact equal likelihood to the comparison group.

I don’t write to criticise the people behind the graphs as I know they are doing important jobs to get information out to a wider audience under time pressure. I also know that there is a lot of explanation that goes on around the chart either in the article or talked about with correspondents which helps explain the complicated concept of odds ratios.

I hope by explaining the thinking behind the designs of our charts and why we think they make them clearer it will help others making odds ratios charts in the future.