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.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset('titanic')
titanic_group_cols = ['class', 'sex', 'alive']
titanic[titanic_group_cols] = titanic[titanic_group_cols].astype('category')
titanic.head()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').
flows = titanic.value_counts(titanic_group_cols, normalize=True).to_frame('n').reset_index()
flows['n'] = (flows['n'] * 1000).astype(int)
flowsPick 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.
# key_col = 'alive'
key_col = 'class'
# key_col = 'sex'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.
gap = 10
for i, col in enumerate(titanic_group_cols):
sort_cols = titanic_group_cols.copy()
sort_cols.insert(0, sort_cols.pop(i)) # Pull out the current col and put it first
print(i, col, sort_cols, sep="\t")
flows[f'{col}_y'] = flows.sort_values(sort_cols).n.cumsum() + flows[col].cat.codes * gap
flows0 class ['class', 'sex', 'alive']
1 sex ['sex', 'class', 'alive']
2 alive ['alive', 'class', 'sex']
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.
for x, col in enumerate(titanic_group_cols):
plt.bar(
x,
flows.n, # y
bottom=flows[f'{col}_y'] - flows.n, # Raise the bottom so it stacks
edgecolor='black',
width=.1
)
plt.text(x + .1, 10, col)
sns.despine(left=True, bottom=True)
plt.xticks([])
plt.yticks([])
plt.title(f"Rudimentary vertical axes ({key_col})")
plt.show()
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.
palette = 'Set1'
cmap = plt.colormaps.get_cmap(palette)
cmapThen 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.
key_cats = flows[key_col].cat.categories
key_catsIndex(['First', 'Second', 'Third'], dtype='str')plt.figure(figsize=(15,10))
for idx, row in flows.iterrows():
# Get the height of the stratum
n = row['n']
# Get the color for this row / ribbon
key_col_val = row[key_col]
key_col_code = key_cats.get_loc(key_col_val)
color = cmap(key_col_code)
# Build the vertical axes
for i, col in enumerate(titanic_group_cols):
# Get the x axis offset of the grouping col, starting with 1
x = i + 1
# Get the y value, i.e. the cumulative value of n, computed already as _y
y = row[f'{col}_y']
# Plot the part of the bar associated with the row
plt.plot([x, x], [y - n, y], lw=10, color=color, solid_capstyle='butt')
# Add a label using plt.text(x, y, text)
plt.text(x + .04, y - n/2, ", ".join(row[titanic_group_cols].values), fontsize=8)
# Plot the ribbon connecting the vertical axes using fill_between
x_vals = [i+1 for i in range(len(titanic_group_cols))] # Again, get the x axis offsets
y_vals = row[[f"{col}_y" for col in titanic_group_cols]].values.astype(float) # Get the pair of y values
plt.fill_between(x_vals, y_vals, y_vals - n, alpha=.25, color=color)
# Add labels to each vertical axis
N = flows.n.sum()
for i, col in enumerate(titanic_group_cols):
plt.text(i+1 - .02, N + N * .05, col.upper())
# Title
plt.title(f"Key: {key_col}")
# Clean up
plt.ylim(0, N + N * .1)
sns.despine(left=True, bottom=True)
plt.xticks([])
plt.yticks([])
plt.show()
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.
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as piopx.parallel_categories(titanic[titanic_group_cols])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.
plotly_cmap = px.colors.qualitative.Set1
plotly_cmap['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)']fig = px.parallel_categories(
titanic,
dimensions=['class','sex','alive'],
color=titanic['class'].cat.codes,
color_continuous_scale=plotly_cmap,
width=800, height=450,
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()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.
penguins = sns.load_dataset('penguins').dropna()
penguins_group_cols = ['species', 'sex', 'island']
penguins[penguins_group_cols] = penguins[penguins_group_cols].astype('category')
penguins.head()fig = px.parallel_categories(
penguins,
dimensions=penguins_group_cols,
color=penguins.species.cat.codes,
color_continuous_scale=plotly_cmap[:len(penguins['species'].unique())],
width=800, height=450,
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()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.
mpg = sns.load_dataset('mpg')
# Create a smaller grouping variable
mpg['period'] = pd.cut(
mpg['model_year'],
bins=[69, 73, 77, 82],
labels=['1970–73', '1974–77', '1978–82']
)
mpg_group_cols = ['origin', 'cylinders', 'period']
mpg[mpg_group_cols] = mpg[mpg_group_cols].astype('category')
mpg[mpg_group_cols]fig = px.parallel_categories(
mpg,
dimensions=['origin', 'cylinders', 'period'],
color=mpg['origin'].cat.codes,
color_continuous_scale=plotly_cmap[:len(mpg['origin'].unique())],
width=800, height=450,
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()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,2It 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,QOne 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.
ucb_data_url = "https://vincentarelbundock.github.io/Rdatasets/csv/datasets/UCBAdmissions.csv"
ucb = pd.read_csv(ucb_data_url).drop('rownames', axis=1)
ucb.head()First, we convert the grouping variables to categories.
ucb_group_cols = ['Admit','Gender', 'Dept']
ucb[ucb_group_cols] = ucb[ucb_group_cols].astype('category')Next, we expand the table so that it has as many rows as there were people in the original pre-aggregated dataset.
ucb_people = (
ucb.loc[ucb.index.repeat(ucb['Freq'])] # Expand the dataframe
.reset_index(drop=True) # Replace the index
.drop('Freq', axis=1) # Drop the Freq column
)
ucb_peopleNow we can draw the diagram:
fig = px.parallel_categories(
ucb_people,
dimensions=['Gender', 'Admit'],
color=ucb_people.Gender.cat.codes,
color_continuous_scale=plotly_cmap[:len(ucb_people.Gender.unique())],
width=600, height=400,
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()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.
fig = px.parallel_categories(
ucb_people,
dimensions=['Gender', 'Dept', 'Admit'],
color=ucb_people.Gender.cat.codes,
color_continuous_scale=plotly_cmap[:len(ucb_people.Gender.unique())],
width=800, height=450,
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()In this diagram, we see the following:
Most women applied to departments through , which reject most applicants of either gender.
Most men applied to and , 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.
X = ucb.pivot_table(index='Dept', columns=['Gender', 'Admit'], values='Freq', aggfunc='sum')
F = X['Female'].Admitted / X['Female'].sum(axis = 1)
M = X['Male'].Admitted / X['Male'].sum(axis = 1)
pd.concat([M,F], keys=['Male','Female'], axis = 1).style.background_gradient(axis=1)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.
hec_data_url = "https://vincentarelbundock.github.io/Rdatasets/csv/datasets/HairEyeColor.csv"
hec = pd.read_csv(hec_data_url).drop('rownames', axis=1)
hec.head()We convert columns and expand rows.
hec_group_cols = ['Hair', 'Eye', 'Sex']
hec[hec_group_cols] = hec[hec_group_cols].astype('category')
hec_people = hec.loc[hec.index.repeat(hec['Freq'])].reset_index(drop=True).drop('Freq', axis=1)
hec_people.sample(5)Let’s also create our own color scheme, to match hair color.
hair_colors = {c:c.lower() for c in hec.Hair.cat.categories}
hair_colors{'Black': 'black', 'Blond': 'blond', 'Brown': 'brown', 'Red': 'red'}hair_colors['Blond'] = 'gold'
hair_colors['Brown'] = 'chocolate'
hair_colors['Red'] = 'orange'fig = px.parallel_categories(
hec_people,
dimensions=hec_group_cols,
color=hec_people['Hair'].cat.codes,
color_continuous_scale=list(hair_colors.values()),
width=800, height=450,
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()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.
vacc_data_url = "https://virginia.box.com/shared/static/qmqjw749ybstm365e3p2sw2lvv09qqeb.csv"
vacc = pd.read_csv(vacc_data_url)
vacc.head()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.
vacc.query("subject == 3")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.
vacc['year'] = vacc['start_date'].str[:4]
vacc.head()We widen the table and add a column for frequency.
vacc_wide = (
vacc
.pivot(index='subject', columns='year', values='response')
.join(vacc[['subject','freq']].drop_duplicates().set_index('subject'))
)
vacc_wideSince this is a count table, we need to expand it.
vacc_wide_exp = (
vacc_wide
.loc[vacc_wide.index.repeat(vacc_wide['freq'])]
.reset_index(drop=True)
.drop('freq', axis=1)
)
vacc_wide_exp.index.name = 'subject_exp'
vacc_wide_exp = vacc_wide_exp.astype('category')
vacc_wide_expAnd here we visualize it:
fig = px.parallel_categories(
vacc_wide_exp,
dimensions=vacc_wide_exp.columns,
color=vacc_wide_exp['2010'].cat.codes,
color_continuous_scale=plotly_cmap,
width=800, height=450
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()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.
polpan_data_url = "https://virginia.box.com/shared/static/3lqirf6hzd702y24hoyne6spb5iyn08q.csv"
polpan = pd.read_csv(polpan_data_url)
polpan.head()Here we clean up the column names and convert the groups to categories.
polpan.columns = [col.replace("party", "") for col in polpan.columns]
group_cols = ['2007', '2011', '2015']
polpan[group_cols] = polpan[group_cols].astype('category')Next, we expand the dataframe.
polpan_exp = polpan.loc[polpan.index.repeat(polpan['n'])].reset_index(drop=True).drop('n', axis=1)
polpan_exp# parties = polpan[group_cols].stack().unique()
# partiesfig = px.parallel_categories(
polpan_exp,
dimensions=polpan_exp.columns,
color=polpan_exp['2007'].cat.codes,
color_continuous_scale=plotly_cmap[:len(polpan_exp['2007'].unique())],
width=800, height=450
)
fig.update_traces(line_shape='hspline')
fig.update_layout(coloraxis_showscale=False)
fig.show()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.
refugees_data_url = "https://virginia.box.com/shared/static/i8unovg5od58s2qlkln25i456d7kpabj.csv"
refugees = pd.read_csv(refugees_data_url)
refugees.head()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.
refugees_wide = refugees.pivot(index='country', columns='year', values='refugees')
refugees_widepx.parallel_categories(
refugees_wide.reset_index(),
dimensions=[2003,2004,2005]
)The right picture here is a time series, with years on the x axis and one series per country.
(refugees
.pivot(index='year', columns='country', values='refugees')
.div(1e6)
.plot
.area(figsize=(10, 5), cmap='Set1', ylabel='Refugees (millions)')
)
plt.legend(bbox_to_anchor=(1, 1))
sns.despine()
plt.show()
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_categoriesneeds a wide table with one row per observation and one column per axis.Tidy (long) repeated measures need a
pivot; counted tables needindex.repeatwithcounts.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.