2

我必须将matplotlib生成的一些极坐标图上的HTML可点击地图关联起来,所以我需要一种方法将数据坐标转换为图的像素坐标。Python - 在matplotlib中使用极坐标散点图进行坐标转换

的代码,改编自,是:

# 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(红色)绘制的点,我画的那些以下坐标:

Difference between the plotted points and the Figure coordinates I get

可能是什么回事? 感谢您的帮助!

更新2017年8月3日

的“延伸”,是更加古怪:我试图绘制半径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对应于我* PI/2 +π/ 4的角度(其中,i = 0,1,2,3)遭受“蚀刻”。事实上,即使通过查看它们的坐标也可以看出:对于i = 0,2,4,6,应该是| x [(i + 4)%8] -x [i] |。 = | y [(i + 4)%8] -y [i] |,但似乎并非如此。

回答

0

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

Inconsistent figure coordinates in matplotlib with equal aspect ratio

的问题是,设置方面等于轴的尺寸和位置时,只能是一旦绘制到画布上,由matplotlib决定。在绘制数据之前,它无法知道轴在最终图中的位置。

最简单的解决方法是调用

fig.canvas.draw() 

绘图命令后立即但做任何改造 作品前。通过这种方式,该图被绘制到画布上,同样应用 ;从这一点开始,正确的转换是 可用。