Matplotlib艺术家在放大时保持相同的大小?

时间:2011-04-15 15:24:14

标签: python matplotlib

我正在使用matplotlib在图表上绘制一些艺术家(特别是几个矩形)。我想以某种方式锚定这些,以便无论使用什么缩放级别它们都保持相同的大小。我已经使用谷歌搜索,我已阅读大部分艺术家文档,并没有运气找到我需要锚定矩形大小的功能。

我喜欢详细说明如何执行此功能的答案,但如果您能让我知道如何执行此操作,或者甚至向我提供一些关键字以使我的Google搜索更有效,我真的很感激:)

谢谢!

1 个答案:

答案 0 :(得分:3)

只需将transform=ax.transAxes关键字应用于PolygonRectangle实例即可。如果将补丁锚定到图形而不是轴上更有意义,也可以使用transFigureHere 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()
相关问题