Matplotlib艺术家在放大时保持相同大小?
我正在使用matplotlib这个工具在图表上画一些图形,具体来说是几个矩形。我希望这些矩形能够固定大小,无论我怎么放大或缩小图表,它们的大小都不变。我在网上查了很多资料,也看了大部分的文档,但就是找不到能让我固定矩形大小的函数。
我希望能得到一个详细的解答,告诉我怎么实现这个功能。如果你能简单说一下怎么做,或者给我一些关键词,让我在网上搜索时更有效率,我会非常感激的 :)
谢谢!
1 个回答
4
只需要在 Polygon
或 Rectangle
的实例中加上 transform=ax.transAxes
这个关键词就可以了。如果你觉得把图形固定在整个图表上更合适的话,也可以使用 transFigure
。这里有关于变换的教程。
下面是一些示例代码:
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()