如何在Pyplot的所有子块之上设置一个主标题?

2024-03-28 09:10:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pyplot。我有4个子批次。如何将一个主标题设置在所有子批次之上?title()将其设置在最后一个子块之上。


Tags: 标题title子块pyplot个子
3条回答

当我将此应用于我自己的绘图时,我发现以下几点很有用:

  • 我更喜欢使用fig.suptitle(title)而不是plt.suptitle(title)的一致性
  • 当使用fig.tight_layout()时,标题必须用fig.subplots_adjust(top=0.88)移位
  • 关于字体大小,请参见答案below

示例代码取自matplotlib文档中的subplots demo,并使用主标题进行调整。

A nice 4x4 plot

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()

使用^{}^{}

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()

enter image description here

如果子批次也有标题,则可能需要调整主标题大小:

plt.suptitle("Main Title", size=16)

相关问题 更多 >