如何在matplotlib中插入子块下面的文本?

2024-05-23 18:37:20 发布

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

我正在使用matplotlib

#Plot
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(8,8))
gs1 = gridspec.GridSpec(1, 2)
gs1.update(wspace=0.025, hspace=0.05)  # set the spacing between axes.

ax1 = plt.subplot(gs1[0])
ax2 = plt.subplot(gs1[1])
ax1.axis('off')
ax1.set_xlabel('(a)')
ax2.axis('off')
ax2.set_xlabel('(b)')

因为我必须关闭图形中的轴,因此,我使用了ax1.axis('off')。现在,我想在每个子批次下面插入图形描述,如(a),(b)。我使用了xlabel,但由于函数axis('off'),它无法工作。我可以通过使用.text函数有其他选择,但它需要已知的位置。在我的例子中,文本必须位于每个子批次的下方和中间。我怎样才能实现它。谢谢 我的预期结果是

enter image description here


Tags: 函数import图形matplotlibaspltgs1set
1条回答
网友
1楼 · 发布于 2024-05-23 18:37:20

问题是,如果设置了axis("off"),那么xlabel就是removed from the figure(以及属于axis的所有其他艺术家)。

但是,可以使用轴正下方的一些普通文本标签来模拟xlabel。

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(8,8))
gs1 = gridspec.GridSpec(1, 2)
gs1.update(wspace=0.025, hspace=0.05)  # set the spacing between axes.

ax1 = plt.subplot(gs1[0])
ax1.imshow([[0,1],[2,1]])
ax2 = plt.subplot(gs1[1])
ax2.imshow([[2,1],[0,1]])

ax1.axis('off')
ax2.axis('off')

ax1.text(0.5,-0.1, "(a) my label", size=12, ha="center", 
         transform=ax1.transAxes)
ax2.text(0.5,-0.1, "(b) my other label", size=12, ha="center", 
         transform=ax2.transAxes)

plt.show()

enter image description here

更改-0.1将在轴和文本之间提供或多或少的空间。

相关问题 更多 >