Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Alluvial Diagrams

DS 2023 | Communicating with Data

Overview

An alluvial diagram shows how the observations in a dataset split and combine across a series of categorical variables.

Each categorical variable gets its own vertical axis.

Each category value on an axis is shown as a block, called a stratum, with height proportional to its count.

Bands called flows or ribbons connect the strata on neighboring axes.

The width of a flow stands for the number of observations that share both categories.

Every observation travels through every axis, so the total height of each axis is the same.

Use Cases

Cross-classification: how one population splits along several categories at once, e.g. who survived the Titanic, by class and sex.

Contingency tables: making a multi-way table of counts visible, e.g. admissions to a university by department and gender.

Repeated measures: the same subjects observed at several times, e.g. students changing majors from semester to semester.

Creating an alluvial diagram from scratch

Think of an alluvial diagram as something like a connected set of stacked bar charts.

Let’s create the bars and show how they are connected into an alluvial.

We will use the titanic dataset and class, sex, and alive as our group variables.

To prepare the data, we will first convert the group variables to categorical data types.

Loading...

Since we want to compare three columns — class, sex, and alive — we use value_counts to get the number of observations for each combination.

This tells us how much data “flows” from one variable to another.

For example, we can see that 336 observations (people) flow from being class = 'Third' and sex = 'male' to not surviving (alive = 'no').

Loading...

Pick a key column

Before we construct the vertical axes and their strata, we need to pick a grouping variable.

This variable that will be used to color the ribbons.

Create the vertical axes and strata

Next, we compute the strata for each vertical axis.

These can be acquired by sorting the columns by the axis variable, followed by the other variables, and then computing the cumulative sums.

We also add a little gap between each category for each variable.

0	class	['class', 'sex', 'alive']
1	sex	['sex', 'class', 'alive']
2	alive	['alive', 'class', 'sex']
Loading...

You can see how the cumulative sums and gaps will be used to construct the vertical axes and strata.

In the stacked bar chart below, each column shows the same data, just grouped and sorted differently.

<Figure size 640x480 with 1 Axes>

Plot the diagram

Now, we plot the vertical axes, strata, and ribbons.

First, we’ll pick a suitable colormap to color the strata and ribbons.

Loading...

Then we get the category object for our key_col so we can grab the category code for the value of the key_col at runtime.

Index(['First', 'Second', 'Third'], dtype='str')
<Figure size 1500x1000 with 1 Axes>

Notice how much of the Third-class stratum flows into no.

Using Plotly

Now let’s use Plotly to create an alluvial diagram from the same data.

It does a much better job of it, but the logic behind the diagram is the same.

Loading...

We can see the three axes and the flows between them.

Note that the plot is interactive:

  • Hovering over an element reveals information about it.

  • You can also drag a stratum up or down to reorder it.

Coloring by a variable

Let’s color the flows by whether the passenger survived.

Let’s also set line_shape='hspline' to curve the flows, which makes them easier to follow.

We’ll use the same palette we use above, this time from Plotly’s colors module.

['rgb(228,26,28)', 'rgb(55,126,184)', 'rgb(77,175,74)', 'rgb(152,78,163)', 'rgb(255,127,0)', 'rgb(255,255,51)', 'rgb(166,86,40)', 'rgb(247,129,191)', 'rgb(153,153,153)']
Loading...

From this diagram we can see that most first-class passengers survived, and most third-class passengers did not.

But we also notice that about two thirds of the survivors were women, and most of the men did not survive.

Tidy data

Most tidy tables can be visualized using alluvials, as long as you want to visualize the categorical (or binnable) variables.

The fact that each row is an observation means that individual entities can be traced across the ribbons connecting the vertical axes.

Let’s demonstrate this with some familiar datasets.

Penguins

Let’s look at how the grouping variables of the Penguins dataset are related.

Loading...
Loading...

Notice the flows that are missing.

  • Gentoo live only on Biscoe, and Chinstrap only on Dream.

  • Adelie are the only species found on all three islands.

An alluvial diagram shows the absence of a combination as clearly as its presence.

Notice also that sex doesn’t matter much in the diagram since the data are balanced over that variable.

Cars

Numeric measurement variables can be axes too, as long as they have only a few distinct values.

Here cylinders has five values, and we bin model_year into three periods.

Loading...
Loading...

Nearly every eight-cylinder car is American.

Follow the 8 stratum into the last period and notice how much thinner it gets after the oil crises.

Aggregated data

Many datasets come already counted: instead of one row per observation, they have one row per combination, with a frequency column showing how many observations have this combination.

For this kind of table to work with parallel_categories, we need to exand it, so that each observation is represented as a row.

For example, if data looks like this:

A,B,C,5
A,D,Q,2

It would need to be converted to this:

A,B,C
A,B,C
A,B,C
A,B,C
A,B,C
A,D,Q
A,D,Q

One way to achieve this effect in Pandas is by using df.index.repeat(freq_col).

College admissions

Here is some data about college admissions to Cal Berkeley from 1973.

Loading...

First, we convert the grouping variables to categories.

Next, we expand the table so that it has as many rows as there were people in the original pre-aggregated dataset.

Loading...

Now we can draw the diagram:

Loading...

From this diagram, we see that, overall, women are admitted at a lower rate than men.

Now let’s add the department in the middle.

Loading...

In this diagram, we see the following:

  • Most women applied to departments CC through FF, which reject most applicants of either gender.

  • Most men applied to AA and BB, which admit most applicants.

So, one reason for lower admission rates for women may have been that they tended to apply to harder departments.

Let’s check the rates directly.

Loading...

Within four of the six departments, women were admitted at a higher rate than men.

This reversal is called Simpson’s paradox.

The two-axis diagram suggests one story, and the three-axis diagram tells the opposite one.

Which axes we include is a claim about what matters.

Hair and eye color

Let look at another table with counts instead of individuals for observations.

Loading...

We convert columns and expand rows.

Loading...

Let’s also create our own color scheme, to match hair color.

{'Black': 'black', 'Blond': 'blond', 'Brown': 'brown', 'Red': 'red'}
Loading...

Most blond-haired people have blue eyes, and most blue-eyed people have blond or brown hair.

What about green eyes?

Wide data

Finally, we can also visualize wide data with an alluvial, where vertical axes represent subsets of the data grouped according some sequential variable, such as year.

Alluvials like this can show how people or things change behavior over time.

Here’s an example from a flu vaccine dataset.

Changing minds about the flu vaccine

The vaccinations shows the results of three surveys, each associated with a year.

Each survey tracks a profile, called a subject, and associates it with a response to a question about how often they take a vaccine.

The freq variable shows the number of respondents with that profile.

Loading...

You can see here that subject is repreated 3 times, one for each survey, and always has the same freq value but differing response values.

Loading...

Let’s create a grouping column out of the date and use it to widen the dataframe.

We want to have subjects as rows, years as columns, and responses as values.

Loading...

We widen the table and add a column for frequency.

Loading...

Since this is a count table, we need to expand it.

Loading...

And here we visualize it:

Loading...

Notice how many respondents are Missing in 2015: more than half of them.

Yet almost all of them answer again in 2016.

Drag the 2015 axis to the end so that 2010 sits next to 2016.

Now we can see that most people who said Always in 2010 still said Always six years later.

The Sometimes group is the least stable.

Voters switching parties

Here’s another table to show changing behavior over time.

The polpan table follows Polish voters through three parliamentary elections.

It is wide already, with a count column n.

Loading...

Here we clean up the column names and convert the groups to categories.

Next, we expand the dataframe.

Loading...
Loading...

How many 2007 PO voters stayed with PO in 2015?

Where did the rest go?

When alluvial diagrams mislead

Flows imply that the same individuals are being tracked

The alluvial package also includes UNHCR refugee counts for ten countries from 2003 to 2013.

Loading...

This table has one row per country per year.

It counts different people each year, though, so nothing connects a refugee in 2003 to a refugee in 2004.

If we pivot year onto the columns, there is nothing to put in the cells but a number, and parallel_categories has no categories to connect.

Loading...
Loading...

The right picture here is a time series, with years on the x axis and one series per country.

<Figure size 1000x500 with 1 Axes>

Axis order changes the story

The flows connect only neighboring axes.

In the Berkeley example, putting Dept between Gender and Admit revealed something that Gender → Admit hid.

Try dragging the axes in any of the diagrams above to see how the picture changes.

Too many categories

Every new category multiplies the number of possible flows.

Bin numeric variables, and lump rare categories into Other, before plotting.

Color can follow only one axis

We colored each diagram by a single variable.

Everything else must be read from the positions of the flows, which is harder.

Choose the coloring variable that carries your main question.

Summary

  • An alluvial diagram shows how observations divide across a sequence of categorical axes.

  • px.parallel_categories needs a wide table with one row per observation and one column per axis.

  • Tidy (long) repeated measures need a pivot; counted tables need index.repeat with counts.

  • Color by one variable, fix the order of categories, and keep the number of categories small.

  • Only draw flows when the same observations really do pass through every axis.