Creating Shared Axis Labels for Matplotlib Subplots

Introduction

When creating multiple subplots using matplotlib, it’s common to share certain elements, like axis labels or titles. This is particularly useful when the data plotted across these subplots has a shared context in terms of units or variables represented on their axes. Sharing axis labels can help maintain clarity and avoid redundancy, allowing for a cleaner presentation.

In this tutorial, we’ll explore several techniques to set common x-axis and y-axis labels for multiple subplots within a single figure using matplotlib, the popular plotting library in Python.

Understanding Subplots

Before diving into shared axis labeling, it’s crucial to understand how subplots work. In matplotlib, subplots are individual axes or plots that share one or both of their axes with other subplots.

You can create a subplot layout by specifying rows and columns:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 1)  # Creates a figure with two rows and one column of subplots.

The axs object is an array containing the individual Axes objects for each subplot.

Techniques to Share Axis Labels

Method 1: Using Invisible Subplot Overlay

One method involves adding an invisible ‘big’ subplot that spans all your subplots. This big subplot acts as a canvas for shared axis labels:

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Create invisible overlay subplot
ax_big = fig.add_subplot(111, frame_on=False)  
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)  # Hide the ticks

ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Common axis labels on the invisible subplot
ax_big.set_xlabel('Common X-axis Label')
ax_big.set_ylabel('Common Y-axis Label')

plt.show()

Method 2: Using fig.text()

matplotlib provides a function called fig.text() that allows you to place text at specific coordinates in figure coordinates:

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(2, 1)

# Add data to subplots
ax1.loglog(x, y1)
ax2.loglog(x, y2)

# Set common axis labels using fig.text()
fig.text(0.5, 0.04, 'Common X-axis Label', ha='center')
fig.text(0.06, 0.5, 'Common Y-axis Label', va='center', rotation='vertical')

plt.show()

Method 3: Using subplots() with Shared Axes

Another approach is to create subplots with shared axes from the start using plt.subplots(). This method automatically aligns labels and ticks across subplots:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(3, 4, sharex=True, sharey=True)

# Add a superordinate axes without frame for the common labels
fig.add_subplot(111, frame_on=False)
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)  # Turn off axis lines and ticks

plt.xlabel('Common X-axis Label')
plt.ylabel('Common Y-axis Label')

plt.show()

Method 4: Using supxlabel and supylabel (Matplotlib 3.4.0+)

For users of matplotlib version 3.4.0 or later, new methods called supxlabel() and supylabel() provide an even more straightforward way to set shared labels:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0.01, 10.01, 0.01)
y = 2 ** x

fig, (ax1, ax2) = plt.subplots(2, 1, constrained_layout=True)

# Individual subplot settings
ax1.loglog(y, x)
ax2.loglog(x, y)

ax1.set_title('First Subplot')
ax2.set_title('Second Subplot')

# Shared axis labels using supxlabel and supylabel
fig.supxlabel('Common X-axis Label')
fig.supylabel('Common Y-axis Label')

plt.show()

Method 5: Using plt.setp()

Finally, you can use the plt.setp() function to set properties on an array of axes:

import matplotlib.pyplot as plt
import numpy as np

# Create a grid of subplots
fig, axs = plt.subplots(3, 3, figsize=(15, 8), sharex=True, sharey=True)

# Populate the subplots with data
for i, ax in enumerate(axs.flat):
    ax.scatter(*np.random.normal(size=(2,200)))
    ax.set_title(f'Subplot {i+1}')

# Set shared x-axis label on the bottom row and y-axis label on the left column
plt.setp(axs[-1, :], xlabel='Common X-axis Label')
plt.setp(axs[:, 0], ylabel='Common Y-axis Label')

plt.show()

Conclusion

This tutorial covered several methods to add common axis labels for subplots using matplotlib. Each method has its use case depending on the version of matplotlib you’re using and your specific requirements. Whether you need a quick solution or a more advanced one, these techniques will help you create plots with shared context and improve readability.

Remember that choosing the right subplot labeling technique depends on factors like aesthetic preference, plot complexity, and compatibility with your version of matplotlib. Experiment with different approaches to determine which best suits your visualization goals.

Leave a Reply

Your email address will not be published. Required fields are marked *