I'm using matplotlib to draw some arti开发者_Go百科sts (a couple rectangles, specifically) on a graph. I'd like to anchor these somehow so that they remain the same size no matter what zoom level is used. I've used google to search and I've read through most of the artist documentation and have had no luck finding what function I need to anchor the rectangle size.
I'd love an answer detailing how to perform this functionality, but if you could just let me know roughly how to do this, or even throw me some keywords to make my google search more effective, I'd really appreciate it :)
Thanks!
Simply apply the transform=ax.transAxes
keyword to the Polygon
or Rectangle
instance. You could also use transFigure
if it makes more sense to anchor the patch to the figure instead of the axis. Here is the tutorial on transforms.
And here is some sample code:
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()
If you do not want to place your polygon using axis coordinate system but rather want it positioned using data coordinate system, then you can use the transforms to statically convert the data before positioning. Best exemplified here:
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()
精彩评论