如何使用Pyplot在所有子图上方设置单个主标题?

Jak*_* M. 184 python matplotlib

我在用pyplot.我有4个子图.如何在所有子图上方设置单个主标题?title()将它设置在最后一个子图上方.

unu*_*tbu 245

使用pyplot.suptitleFigure.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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 注意,它是`plt.suptitle()`而不是`plt.subtitle()`.我一开始没有意识到这一点并且出现了一个令人讨厌的错误!:d (5认同)

Ale*_*ane 101

在将这个应用到我自己的情节时,我认为有用的几点:

  • 我更喜欢使用fig.suptitle(title)而不是使用的一致性plt.suptitle(title)
  • 使用fig.tight_layout()标题时必须转移fig.subplots_adjust(top=0.88)
  • 请参阅下面有关fontsizes的答案

示例代码取自matplotlib docs中的subplots demo并使用主标题进行调整.

一个不错的4x4情节

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()
Run Code Online (Sandbox Code Playgroud)

  • 简单地添加 `figure.suptitle()` 是不够的,因为子图的标题会与 suptitile 混合,`fig.subplots_adjust(top=0.88)` 是好的。 (3认同)

pen*_*ous 40

如果你的子图也有标题,你可能需要调整主标题大小:

plt.suptitle("Main Title", size=16)
Run Code Online (Sandbox Code Playgroud)

  • 在python 2.7中,它是**fontsize**而不是**size**.`plt.suptitle("Main Title",fontsize = 16)` (8认同)