如何在matplotlib中将标题放在图形的底部?

问题描述 投票:0回答:3

我使用 matplotlib 绘制一个包含四个子图的图形,并且

set_title
方法将标题(
(a) (b) (c) (d)
)放在每个子图的顶部,请参阅以下代码示例。


fig = pyplot.figure()
ax = fig.add_subplot(1, 4, 1)
ax.set_title('(a)')

但我想将每个标题放在每个子图的底部。我无法通过 matplotlib 文档和 google 弄清楚它。所以我需要你的帮助,非常感谢。

python matplotlib title figure
3个回答
6
投票

由于您不使用 x 轴,您只需将 xlabel 设置为标题即可,应注意定位:

ax.set_xlabel('this really is a title disguised as an x label')

编辑:

尝试根据人物高度偏移标题,我希望这有效:

size = fig.get_size_inches()*fig.dpi # get fig size in pixels
ax.set_title('(a)', y=-size[1]) # increase or decrease y as needed

3
投票

这是一个小的Python函数,可以绘制没有轴的图像。每个子图像底部的标题。 images 是一个 n 长度数组,其中包含内存中的图像,labels 是一个 n 长度数组,包含相应的标题:

from matplotlib import pyplot

def plot_image_array_gray(images, labels):
  for i in range(0, len(labels)):
    ax = pyplot.subplot(1, len(labels), i + 1)
    pyplot.axis('off')
    pyplot.text(0.5, -0.1, labels[i], \
      horizontalalignment='center', verticalalignment='center', \
      transform=ax.transAxes)
    pyplot.imshow(images[i], cmap=pyplot.cm.gray)

  pyplot.tight_layout()
  pyplot.show()

使用示例

# code to load image_a and image_b 
# ...
plot_image_array_gray((image_a, image_b), ("(a)", "(b)"))

3
投票

如果您使用 ax,请使用以下行,然后调整 'y' 的值。

ax.set_title('(d)',y=-0.2,pad=-14)

您可以调整 y 值,这里我使用“负”值,因为我希望我的标签位于子图中图形的底部。

我还没查过pad是什么。

© www.soinside.com 2019 - 2024. All rights reserved.