首页 > 解决方案 > 使用 mplot3d 旋转默认坐标轴方向

问题描述

我正在绘制来自 3D 成像的数据,其中参考坐标系非常规定向。具体来说,对于仰卧(面朝上)的患者,+X 方向指向患者的左侧,+Y 指向地板,+Z 指向患者头部的方向。它仍然是一个右手坐标系。如果我使用 ax.view_init() 设置一个接近这个方向的视点,我会发现交互式操作非常糟糕。到目前为止,我的解决方案是通过旋转矩阵传递我的数据点,以将其映射到世界空间中的这个方向并绘制结果。我也可以调用 ax.plot(-z, x, -y) 来获得相同的结果。这是功能性的,但会使代码混乱,我发现它容易出错。

有没有办法将我的转换矩阵嵌入到 mplot3d 处理链中,以便自动发生?对于它确实执行的转换,文档仍然有点不完整,我无法确定从哪里开始,尽管我认为它可能是可能的。

更具体一点,这里的代码通常在左侧绘制,而我更喜欢在右侧绘制:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')

X, Y, Z = axes3d.get_test_data(0.05)

pts = np.vstack((X.flatten(), Y.flatten(), Z.flatten(), np.ones_like(X.flatten())))
xf = np.array([
    [0., 0.,-1., 0.],
    [1., 0., 0., 0.],
    [0.,-1., 0., 0.],
    [0., 0., 0., 1.]
])
pts = xf @ pts
xt = pts[0].reshape((X.shape))
yt = pts[1].reshape((Y.shape))
zt = pts[2].reshape((Z.shape))

ax1.plot_surface(X, Y, Z, rstride=10, cstride=10)
ax2.plot_surface(xt, yt, zt, rstride=10, cstride=10)
for ax in (ax1, ax2):
    for ff in (ax.set_xlim, ax.set_ylim, ax.set_zlim):
        ff(-50, 50)

常规和所需方向的示例图

标签: pythonmatplotlibcoordinate-transformationmplot3d

解决方案


推荐阅读