When working with complex visualizations that involve multiple layers, controlling the order of these layers is essential for creating clear and informative plots. In this post, we'll explore how to rearrange layers in Matplotlib and Seaborn plots using the zorder
parameter, with an example using a weather dataset from BigQuery public datasets.
Setup
Let’s use a weather dataset from BigQuery public datasets, with the daily temperatures in New York City.
# Import libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
%%bigquery df
# Get NYC temperatures as sample data
SELECT
year,
mo AS month,
AVG(temp) AS temp
FROM `bigquery-public-data.noaa_gsod.gsod*`
WHERE
wban = '94728'
AND CAST(mo AS INT64) <= 6
GROUP BY year, mo
ORDER BY year, mo
We'll also compute the quartiles for each month:
# Compute quartiles for each month
quartiles = (
df
.groupby('month')
.quantile([.25, .75])
.reset_index()
.pivot(index='month', columns='level_1')
.set_axis(['low', 'high'], axis=1)
)
Reorder plot layers with z-order
When plotting multiple layers, the order in which they are drawn may not always match the sequence of the code. This can lead to unwanted visual effects, such as lines being hidden behind filled areas.
To rearrange the layers order, you can specify their z-index using the zorder
parameter:
# Plot with default layers z-order
fig, ax = plt.subplots(1,2, figsize=(14,6))
sns.lineplot(data=df, x='month', y='temp', units='year', estimator=None, color='grey', alpha=.5, ax=ax[0])
ax[0].fill_between(x=quartiles.index, y1=quartiles['low'], y2=quartiles['high'], alpha=.5)
ax[0].set_title("Without z-order")
# Specify z-order
sns.lineplot(data=df, x='month', y='temp', units='year', estimator=None, color='grey', alpha=.5, ax=ax[1], zorder=1)
ax[1].fill_between(x=quartiles.index, y1=quartiles['low'], y2=quartiles['high'], alpha=.5, zorder=2)
ax[1].set_title("With z-order specified");
The zorder
parameter controls the stacking order of the plot elements. A higher zorder
value means the element will be drawn on top of elements with lower zorder
values.