按轴分数定位文本


问题内容

有没有一种方法可以按轴的分数在图形中放置文本?我希望所有图的文本都在同一位置,而不管它们在x和y中的范围是否不同。此功能在ax.annotate()中,但我需要添加额外的“
xy”参数,这会使我的代码更难阅读。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10)) 
ax.annotate('Correct Position', xy=(0, 0), xytext=(0.4, 0.7), textcoords='axes fraction')
ax.text(0.4, 0.7, 'Incorrect Position')

plt.show()

问题答案:

您可以使用transform关键字:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure() 
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.arange(10),12*np.arange(10)) 
ax.text(0.4, 0.7, 'Correct Position', transform=ax.transAxes)

plt.show()