How to set a single main title for all the subplots in Matplotlib?
0 1193
How to Add a Main Title for All Subplots in Matplotlib
When creating multiple subplots using Matplotlib, it’s often helpful to include a single title that summarizes the entire figure. This can be done using the suptitle() method, which places a main title above all subplots.
Using suptitle() to Set a Figure-Wide Title
The suptitle() function belongs to the matplotlib.pyplot module. It allows you to define a main title for the whole figure, rather than individual subplot titles. Key parameters include:
t: The main title text.xandy: Positioning coordinates (defaults center at top).fontsize: Size of the title text.fontweight: Weight of the font like 'bold' or 'light'.haandva: Horizontal and vertical alignment.
Example: Simple Main Title on 2x2 Subplots
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 2)
for i in range(2):
for j in range(2):
ax[i, j].plot(np.random.rand(10))
fig.suptitle('Main Title Across All Subplots', fontsize=16)
plt.tight_layout()
plt.show()
This example plots four subplots in a 2x2 grid and places a single, centered title above them using suptitle().
Improving Layout with tight_layout()
Adding a figure-wide title can sometimes cause overlap with subplot elements. To resolve this, use tight_layout() along with the rect parameter:
plt.tight_layout(rect=[0, 0, 1, 0.95])
This adjusts the layout to leave some space at the top for the title.
Customizing the Title Appearance
fig.suptitle('Stylized Main Title', fontsize=20, fontweight='bold', ha='center')
You can easily adjust font size, weight, and alignment to style the main title as needed.
Conclusion
The suptitle() function is a simple and effective way to set a central title for all subplots in Matplotlib. Combined with layout adjustments like tight_layout(), it ensures your plots are both informative and visually well-organized.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:


Comments
Waiting for your comments