Explain Codes LogoExplain Codes Logo

How to add a title to each subplot

python
matplotlib
plotting
subplots
Alex KataevbyAlex Kataev·Nov 22, 2024
TLDR

In matplotlib, call set_title on each Axes instance to add titles to your subplots. Assume you've a 2x2 subplot grid, here's an example:

import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 2) titles = ["Title 1", "Title 2", "Title 3", "Title 4"] for ax, title in zip(axs.ravel(), titles): ax.set_title(title) # Surprise! Each of your subplots now has a title! plt.tight_layout() # Keep the peace among subplots, no overlaps! plt.show()

Use ravel() for easy traversing of any grid shape. tight_layout() steps in to manage spacing. Modify the number of subplots and titles as per your needs!

More than setting titles: advanced subplot tweaking

Loop through subplots for dynamic titles

Have many subplots? Slap titles on all with a loop:

fig, axs = plt.subplots(nrows=3, ncols=3) for i, ax in enumerate(axs.flat): # Flat iterators: like flat Earth, but real! ax.set_title(f'Subplot {i+1}') # naming your baby plots plt.show()

Spice up your titles with alternatives

Not a fan of mainstream set_title? Meet its alter ego, title.set_text :

ax.title.set_text('My Subplot Title') # unconventional way, yet just as cool

Set the stage: Add a main title

fig.suptitle brings forth main titles that overshadow all subplots:

fig.suptitle('My Main Figure Title', fontsize=16) # 16px, because size matters

Choreographing complex subplot configurations

Subplot titles dance well with complex subplot layouts:

fig, axs = plt.subplots(3, 1, gridspec_kw={'height_ratios': [1, 2, 1]}) axs[0].set_title('Top View') # You have my attention, I'm all ears! axs[1].set_title('Main Scene') # And... Action! axs[2].set_title('Bottom View') # Awesome, but we're done looking up your nostrils!

Taming your layout with tight_layout

Meet tight_layout():

fig.tight_layout(pad=3.0) # More room, less drama among subplots

Subplot title aesthetics: The dressing game

Dress your titles for success with font and position customizations:

ax.set_title('Beautiful Plot', fontdict={'fontsize': 14, 'color': 'green'}, loc='left') # Green, because eco-friendly fonts exist.

Troubleshooting guide: common pitfalls

Ensuring unique titles

Beware, same subplot titles are as confusing as identical twins. Make sure they're unique:

# WRONG: Sets 'One-ring-to-rule-them-all' type of title for ax in axs.flat: ax.set_title('The general title') # I'm general, but I don't rule subplots! # RIGHT: Marks each subplot with unique identifier for index, ax in enumerate(axs.flat): ax.set_title(f'Subplot-{index + 1}') # 'I'm unique, like everyone else'

Tips to avoid title overlap

Titles may overlap, acting like grumpy neighbors. Use tight_layout or constrained_layout to set boundaries:

plt.tight_layout() # Let's make some room for ourselves! # Or alternatively: fig, axs = plt.subplots(2, 2, constrained_layout=True) # Use C-L, also stands for Civilized Layout!

Crafting dynamic title content

Inject content dynamically into your titles. Unleash the power of f-strings or str.format:

ax.set_title(f'Data Plot of {dynamic_value}') # Titles on-the-fly, like your data!