Python - 在matplotlib中用极坐标散点图进行坐标变换

Python - Coordinate transformation with polar scatter plot in matplotlib

我必须在一些用 matplotlib 生成的极坐标图上关联一个 HTML 可点击地图,所以我需要一种方法将数据坐标转换为图形的像素坐标。

改编自How to get pixel coordinates for Matplotlib-generated scatterplot?的代码是:

# Creates 6 points on a ray of the polar plot
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
points, = ax.plot([1,1,1,1,1,1],[0,1,2,3,4,5], 'ro')
ax.set_rmax(5)

x, y = points.get_data()
xy_pixels = ax.transData.transform(np.vstack([x,y]).T)
xpix, ypix = xy_pixels.T
width, height = fig.canvas.get_width_height()
ypix = height - ypix

for xp, yp in zip(xpix, ypix):
    print('{x:0.2f}\t{y:0.2f}'.format(x=xp, y=yp))

这给出了

328.00  240.00
354.80  207.69
381.60  175.38
408.40  143.06
435.20  110.75
461.99  78.44

只有位于图表中心的第一个点是正确的。其他的似乎被移动了,就好像这个数字被水平拉伸了一样。 此图代表matplotlib(红色)绘制的点和我按照坐标绘制的点:

这是怎么回事? 感谢您的帮助!

2017 年 8 月 3 日更新

"stretching" 甚至更奇怪:我试图用这个命令绘制一个内切在半径为 3 的圆中的八面体:

points, = ax.plot([math.pi/4,math.pi/2,3*math.pi/4,math.pi,5*math.pi/4,3*math.pi/2,7*math.pi/4,2*math.pi],[3,3,3,3,3,3,3,3], 'ro')

同样的例程给出了结果

495.01  110.70
328.00  57.14
160.99  110.70
91.81   240.00
160.99  369.30
328.00  422.86
495.01  369.30
564.19  240.00

虽然沿 x 和 y 轴的 4 个点放置正确,但其他 4 个对应于 i*pi/2 + pi/4 角度(其中 i=0,1,2,3)患上了"stretching"。实际上,即使查看它们的坐标也可以看出这一点:对于 i=0,2,4,6,|x[(i+4)%8]-x[i]| 应该为真= |y[(i+4)%8]-y[i]|,而事实并非如此。

这是一个非常棘手的问题,原来这里已经解决了:

The problem is that when setting the aspect to equal the dimensions and positions of the axes can only be determined by matplotlib once something is drawn onto the canvas. Before plotting the data, it cannot know where the axes would reside in the final figure.

The easiest solution is to call

fig.canvas.draw()

right after the plot command but before doing any transformation works. In this way, the figure gets drawn to the canvas, applying the equal aspect; and from this point on, the correct transformations are available.