Matplotlib: ax.format_coord() 在 3D 三角冲浪图中 - 返回 (x,y,z) 而不是 (



我试图重做这个已经回答的问题 Matplotlib - plot_surface :获取写在右下角的 x,y,z 值,但无法获得相同的结果,如那里所述。所以,我有一个这样的代码:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from plyfile import PlyData, PlyElement
#Handle the "onclick" event
def onclick(event):
print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
('double' if event.dblclick else 'single', event.button,
event.x, event.y, event.xdata, event.ydata))
print(gety(event.xdata, event.ydata))
#copied from https://stackoverflow.com/questions/6748184/matplotlib-plot-surface-get-the-x-y-z-values-written-in-the-bottom-right-cor?rq=1
def gety(x,y):
s = ax.format_coord(x,y)
print(s) #here it prints "azimuth=-60 deg, elevation=30deg"
out = ""
for i in range(s.find('y')+2,s.find('z')-2):
out = out+s[i]
return float(out)
#Read a PLY file and prepare it for display
plydata = PlyData.read("some.ply")
mesh = plydata.elements[0]
triangles_as_tuples = [(x[0], x[1], x[2]) for x in plydata['face'].data['vertex_indices']]
polymesh = np.array(triangles_as_tuples)
#Display the loaded triangular mesh in 3D plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(mesh.data['x'], mesh.data['y'], mesh.data['z'], triangles=polymesh, linewidth=0.2, antialiased=False)
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

这样,三角形表面就可以正确显示(尽管速度很慢(。当我将鼠标悬停在绘图上时,我可以在右下角看到表面的 (x,y,z( 坐标。但是当我尝试通过单击鼠标(通过连接的事件处理程序(获取这些坐标时,ax.format_coord(x,y( fction 返回的不是一串笛卡尔坐标,而是一串"方位角=-60 度,海拔=30 度",无论我在绘图中的哪个位置单击,直到表面旋转。然后它返回另一个值。 由此我想这些是当前视图的球面坐标,而不是点击的点,出于某种原因......

有人能发现,我做错了什么吗?如何获取曲面上的笛卡尔坐标?

仅供参考:这一切都与我之前的问题Python:3D图形输入有关,该问题被认为过于宽泛和通用。

按下的鼠标按钮是ax.format_coord返回 3D 图上的角度坐标而不是笛卡尔坐标的触发器。所以一个选择是让ax.format_coord认为没有按下按钮,在这种情况下,它会根据需要返回通常的笛卡尔 x,y,z 坐标。

即使您单击了鼠标按钮,实现此目的的黑客方法也是在调用该函数时将ax.button_pressed(存储当前鼠标按钮(设置为不合理的值。

def gety(x,y):
# store the current mousebutton
b = ax.button_pressed
# set current mousebutton to something unreasonable
ax.button_pressed = -1
# get the coordinate string out
s = ax.format_coord(x,y)
# set the mousebutton back to its previous state
ax.button_pressed = b
return s

最新更新