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

2024-05-15 00:16:22 发布

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

我想把文字放在等宽图的右下角。 我通过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                                              

enter image description here


Tags: textright图形高度plottransformpltequal
1条回答
网友
1楼 · 发布于 2024-05-15 00:16:22

使用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()

enter image description here

如果希望它稍微偏离角点,可以通过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()

enter image description here

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

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()

enter image description here

还可以查看Matplotlib annotation guide以获取更多信息。

相关问题 更多 >

    热门问题