受 Matplotlib here 这个示例的启发,我想做一个类似的。我遇到了以下问题:如何将 matplotlin 图形的坐标与现实世界坐标联系起来?
用下图来说明:
inset_axis
相当精确地位于红点处left_inset_ax = fig.add_axes([1, 0, .05, .05], facecolor='k')
所有四个角(参见黑色方块)myCoordinates=True
我有不同的类型的
inset
图形。其中之一就是下面这个。它们是在 polar
设置中由 生成的
这里给出的一些解决方案看起来很有希望。我以此为基础添加更多功能,如标题、x 和 y 标签、等距非方形设置、不同数量的网格点。方法是
inset_axis
inset_axis
import numpy as np
import matplotlib.pyplot as plt
def scaleXY(xgr,ygr,xT,yT):
xgr = (xgr-xT.min())/(xT.max()-xT.min())
ygr = (ygr-yT.min())/(yT.max()-yT.min())
return xgr, ygr
nx, ny = 150, 60 # choose: number of data
ix = np.linspace(-5, 20, nx)*100
iy = np.linspace(-1, 15, ny)*100
xq, yq = np.meshgrid(ix,iy, indexing='ij') # generate data
dx, dy = 50, 30 # choose
xp,yp = xq[::dx,::dy], yq[::dx,::dy] # select a few of them
xgr, ygr = scaleXY(xp,yp,xq,yq) # scale them to (0..1)
with plt.style.context('fast'):
fig = plt.figure(figsize=(10,10))
ax1 = fig.add_subplot(111)
ax1.scatter(xq,yq, s=5) # plot the base data
ax1.scatter(xp,yp, c='lime', s=300, alpha = 0.6) # plot the testing points
ins = ax1.inset_axes([xgr[2,1], ygr[2,1], 0.2,0.2]) # check the inset positioning
ins = ax1.inset_axes([xgr[1,1], ygr[1,1], 0.2,0.2]) # check the inset positioning
ins = ax1.inset_axes([xgr[0,0], ygr[0,0], 0.2,0.2]) # check the inset positioning
ins = ax1.inset_axes([xgr[2,0], ygr[2,0], 0.2,0.2]) # check the inset positioning
ax1.set_aspect('equal')
title = 'Even more dangerous area'
ax1.set_title(title,fontweight='bold', fontsize=17)
ax1.set_xlabel('x-direction', fontsize=17)
ax1.set_ylabel('y-direction', fontsize=17)
plt.show()
结果,我们可以看到图形的坐标与用户的坐标是分开的。这就引出了一个问题:如何将 matplotlin 图形的坐标与现实世界的坐标联系起来?
我会感谢任何其他正在运行的解决方案的提示 - 谢谢!
inset_axes
告诉
transform=ax.transData
使用数据坐标。
import numpy as np
import matplotlib.pyplot as plt
target_x = [12, 12, 42, 42]
target_y = [7, 13, 13, 7]
fig, ax = plt.subplots()
ax.scatter(target_x, target_y, color='lime')
x0 = target_x[0]
y0 = target_y[0]
width = target_x[2] - target_x[0]
height = target_y[2] - target_y[0]
ax_ins = ax.inset_axes([x0, y0, width, height], transform=ax.transData)
ax.set_xlim(0, 50)
ax.set_ylim(0, 20)
plt.show()
由于 采用projection 和 polar 关键字,因此您可以通过这种方式创建极坐标图作为插图。