我想将文字放在相同方面图的右下角。 我通过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
答案 0 :(得分:41)
使用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()
如果您希望它从角落略微偏移,您可以通过xytext
kwarg(和textcoords
指定偏移来控制xytext
的值的解释方式)。我还在ha
和va
使用horizontalalignment
和verticalalignment
缩写:
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 annotation guide以获取更多信息。