Answers:
使用pyplot.suptitle
或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()
plt.suptitle()
不是plt.subtitle()
。我一开始没有意识到这一点,并且遇到了一个讨厌的错误!:D
将其应用于自己的绘图时,我发现一些要点:
fig.suptitle(title)
而不是plt.suptitle(title)
fig.tight_layout()
标题时,必须与fig.subplots_adjust(top=0.88)
示例代码取自matplotlib文档中的subplots演示,并已通过主标题进行了调整。
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()
figure.suptitle()
是不够的,因为子图的标题会与软化的标题混合在一起,这fig.subplots_adjust(top=0.88)
是很好的。
suptitle
。不过,我还是看到了您的“无耻骇客!” :)