问题:Python/Matplotlib - 如何将文本放在等宽图形的角落

我想把文字放在等宽高图的右下角。我通过 ax.transAxes 设置相对于图形的位置,但我必须根据每个图形的高度比例手动定义相对坐标值。

什么是了解轴高度比例和脚本中正确文本位置的好方法?

 ax = plt.subplot(2,1,1)
 ax.plot([1,2,3],[1,2,3])
 ax.set_aspect('equal')
 ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16)
 print ax.get_position().height

 ax = plt.subplot(2,1,2)
 ax.plot([10,20,30],[1,2,3])
 ax.set_aspect('equal')
 ax.text(1,-0.15, 'text', transform=ax.transAxes, ha='right', fontsize=16)
 print ax.get_position().height                                              

在此处输入图像描述

解答

使用annotate

事实上,我几乎从不使用text。即使我想在数据坐标中放置东西,我通常也想以点为单位偏移一些固定距离,这使用annotate更容易。

举个简单的例子:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))

axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))

for ax in axes:
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                horizontalalignment='right', verticalalignment='bottom')
plt.show()

在此处输入图像描述

如果您希望它从角落稍微偏移,您可以通过xytextkwarg 指定偏移量(和textcoords来控制如何解释xytext的值)。我也在这里使用hava的缩写horizontalalignmentverticalalignment:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))

axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))

for ax in axes:
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                xytext=(-5, 5), textcoords='offset points',
                ha='right', va='bottom')
plt.show()

在此处输入图像描述

如果您尝试将其放置在轴下方,则可以使用偏移量将其放置在点以下设定的距离:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, subplot_kw=dict(aspect=1))

axes[0].plot(range(1, 4))
axes[1].plot(range(10, 40, 10), range(1, 4))

for ax in axes:
    ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16,
                xytext=(0, -15), textcoords='offset points',
                ha='right', va='top')
plt.show()

在此处输入图像描述

另请查看Matplotlib 注释指南了解更多信息。

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐