0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Set Title for Each Subplot in Matplotlib

To set a title for each subplot in matplotlib, use the set_title() method on each subplot's axes object. For example, after creating subplots with fig, axs = plt.subplots(), call axs[i].set_title('Title') for each subplot.
๐Ÿ“

Syntax

When you create multiple subplots using plt.subplots(), it returns a figure and an array of axes objects. You can set the title of each subplot by calling set_title() on each axes object.

  • fig, axs = plt.subplots(nrows, ncols): creates a grid of subplots.
  • axs[i, j].set_title('Title'): sets the title for the subplot at row i and column j.
python
fig, axs = plt.subplots(2, 2)
axs[0, 0].set_title('Top Left')
axs[0, 1].set_title('Top Right')
axs[1, 0].set_title('Bottom Left')
axs[1, 1].set_title('Bottom Right')
๐Ÿ’ป

Example

This example creates a 2x2 grid of subplots and sets a unique title for each subplot using set_title(). It shows how to access each subplot's axes and assign a title.

python
import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, figsize=(8, 6))

axs[0, 0].plot([1, 2, 3], [1, 4, 9])
axs[0, 0].set_title('Quadratic')

axs[0, 1].plot([1, 2, 3], [1, 2, 3])
axs[0, 1].set_title('Linear')

axs[1, 0].plot([1, 2, 3], [1, 8, 27])
axs[1, 0].set_title('Cubic')

axs[1, 1].plot([1, 2, 3], [1, 1, 1])
axs[1, 1].set_title('Constant')

plt.tight_layout()
plt.show()
Output
A 2x2 grid of line plots with titles: 'Quadratic', 'Linear', 'Cubic', and 'Constant' on each subplot respectively.
โš ๏ธ

Common Pitfalls

Common mistakes when setting subplot titles include:

  • Trying to use plt.title() which sets the title for the whole figure, not individual subplots.
  • Not indexing the axes array correctly when there are multiple subplots.
  • For a single subplot, forgetting that axs is not an array but a single axes object.
python
import matplotlib.pyplot as plt

# Wrong: sets title for whole figure, not subplots
fig, axs = plt.subplots(2, 2)
plt.title('Wrong Title')  # This sets one title for entire figure

# Right: set title on each axes
axs[0, 0].set_title('Correct Title')
๐Ÿ“Š

Quick Reference

  • fig, axs = plt.subplots(nrows, ncols): create subplots.
  • axs[i, j].set_title('Title'): set title for subplot at row i and column j.
  • Use plt.tight_layout() to avoid overlapping titles.
  • For single subplot, use ax.set_title('Title') directly.
โœ…

Key Takeaways

Use the set_title() method on each subplot's axes object to set individual titles.
Access each subplot via the axes array returned by plt.subplots().
plt.title() sets the title for the whole figure, not individual subplots.
Use plt.tight_layout() to prevent title and label overlap.
For a single subplot, call set_title() directly on the axes object.