注意
前往末尾下载完整的示例代码。
标题定位#
Matplotlib 可以显示居中的绘图标题,与坐标轴集的左侧对齐,以及与坐标轴集的右侧对齐。

垂直位置是自动选择的,以避免最上面的 x 轴上的装饰(即标签和刻度)
fig, axs = plt.subplots(1, 2, layout='constrained')
ax = axs[0]
ax.plot(range(10))
ax.xaxis.set_label_position('top')
ax.set_xlabel('X-label')
ax.set_title('Center Title')
ax = axs[1]
ax.plot(range(10))
ax.xaxis.set_label_position('top')
ax.xaxis.tick_top()
ax.set_xlabel('X-label')
ax.set_title('Center Title')
plt.show()

可以通过手动为标题指定y关键字参数或在 rcParams 中设置 rcParams["axes.titley"]
(默认值:None
)来关闭自动定位。
fig, axs = plt.subplots(1, 2, layout='constrained')
ax = axs[0]
ax.plot(range(10))
ax.xaxis.set_label_position('top')
ax.set_xlabel('X-label')
ax.set_title('Manual y', y=1.0, pad=-14)
plt.rcParams['axes.titley'] = 1.0 # y is in axes-relative coordinates.
plt.rcParams['axes.titlepad'] = -14 # pad is in points...
ax = axs[1]
ax.plot(range(10))
ax.set_xlabel('X-label')
ax.set_title('rcParam y')
plt.show()

脚本的总运行时间:(0 分钟 2.142 秒)