I am using pyplot
. I have 4 subplots. How to set a single, main title above all the subplots? title()
sets it above the last subplot.
Asked
Active
Viewed 3.9e+01k times
349

Trenton McKinney
- 56,955
- 33
- 144
- 158

Jakub M.
- 32,471
- 48
- 110
- 179
3 Answers
451
Use pyplot.suptitle
or Figure.suptitle
:
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
ax=fig.add_subplot(2,2,i)
ax.imshow(data)
fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()

Will Vousden
- 32,488
- 9
- 84
- 95

unutbu
- 842,883
- 184
- 1,785
- 1,677
-
1Works with `suptitle`. Still, I saw your "shameless hack!" :) – Jakub M. Aug 15 '11 at 15:08
-
13Note, it is `plt.suptitle()` and not `plt.subtitle()`. I did not realize this in the beginning and got a nasty error! :D – Dataman May 10 '16 at 15:40
202
A few points I find useful when applying this to my own plots:
- I prefer the consistency of using
fig.suptitle(title)
rather thanplt.suptitle(title)
- When using
fig.tight_layout()
the title must be shifted withfig.subplots_adjust(top=0.88)
- See answer below about fontsizes
Example code taken from subplots demo in matplotlib docs and adjusted with a master title.
import matplotlib.pyplot as plt
import numpy as np
# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)
axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')
# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)
# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)
plt.show()

Community
- 1
- 1

Alexander McFarlane
- 10,643
- 9
- 59
- 100
-
4Simply adding `figure.suptitle()` is not enough since titles of subplots will mix with suptitile, `fig.subplots_adjust(top=0.88)` is good. – GoingMyWay Mar 22 '19 at 02:28
50
If your subplots also have titles, you may need to adjust the main title size:
plt.suptitle("Main Title", size=16)

pentandrous
- 858
- 1
- 9
- 18
-
11In python 2.7 it is **fontsize** instead of **size**. `plt.suptitle("Main Title", fontsize=16)` – Temak Feb 11 '16 at 17:59