只需将transform=ax.transAxes 关键字应用于Polygon 或Rectangle 实例。如果将补丁锚定到图形而不是轴更有意义,您也可以使用transFigure。 Here is the tutorial on transforms.
下面是一些示例代码:
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
import numpy as np
x = np.linspace(0,5,100)
y = np.sin(x)
plt.plot(x,y)
ax = plt.gca()
polygon = Polygon([[.1,.1],[.3,.2],[.2,.3]], True, transform=ax.transAxes)
ax.add_patch(polygon)
plt.show()
如果您不想使用轴坐标系放置多边形,而是希望使用数据坐标系对其进行定位,那么您可以使用变换在定位前静态转换数据。最好的例子在这里:
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
import numpy as np
x = np.linspace(0,5,100)
y = np.sin(x)
plt.plot(x,y)
ax = plt.gca()
dta_pts = [[.5,-.75],[1.5,-.6],[1,-.4]]
# coordinates converters:
#ax_to_display = ax.transAxes.transform
display_to_ax = ax.transAxes.inverted().transform
data_to_display = ax.transData.transform
#display_to_data = ax.transData.inverted().transform
ax_pts = display_to_ax(data_to_display(dta_pts))
# this triangle will move with the plot
ax.add_patch(Polygon(dta_pts, True))
# this triangle will stay put relative to the axes bounds
ax.add_patch(Polygon(ax_pts, True, transform=ax.transAxes))
plt.show()