You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用带箭头的笛卡尔坐标系可视化旋转矩阵的变换效果?

3D旋转变换矩阵可视化实现

我有一个默认4×4变换矩阵,由3×3旋转矩阵、3×1平移向量和1×3缩放向量组成,默认矩阵如下:

matrix_default= [[1, 0, 0, 0],
                 [0, 1, 0, 0],
                 [0, 0, 1, 0],
                 [0, 0, 0, 1]]

我已经实现了X方向平移的可视化,代码如下:

matrix_translated= [[1, 0, 0, 10],
                    [0, 1, 0, 0],
                    [0, 0, 1, 0],
                    [0, 0, 0, 1]]

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

# 可视化平移效果
ax.scatter(matrix_default[0][3], matrix_default[1][3], matrix_default[2][3], color='r', s=10**2)
ax.scatter(matrix_translated[0][3], matrix_translated[1][3], matrix_translated[2][3], color='black', s=10**2)

plt.show()

(配图:红色点代表原点默认位置,黑色点代表X方向平移10单位后的位置)

现需要实现任意方向旋转的可视化,要求在绘制的点上用带箭头的线构建笛卡尔坐标系展示(参考示例:旋转后带箭头的坐标系示意图)。

补充说明:绕Z轴旋转90°的旋转矩阵示例如下:

matrix_rotated= [[-1, -2, 0, 0],
                 [2, -1, 0, 0],
                 [0, 0, 1, 0],
                 [0, 0, 0, 1]]

希望通过箭头/线表示该旋转的变换效果。


实现代码

import matplotlib.pyplot as plt
import numpy as np

# 默认变换矩阵
matrix_default = np.array([[1, 0, 0, 0],
                           [0, 1, 0, 0],
                           [0, 0, 1, 0],
                           [0, 0, 0, 1]])

# 绕Z轴旋转90°的变换矩阵
matrix_rotated = np.array([[-1, -2, 0, 0],
                           [2, -1, 0, 0],
                           [0, 0, 1, 0],
                           [0, 0, 0, 1]])

# 提取旋转矩阵部分
rotation_matrix = matrix_rotated[:3, :3]

# 原坐标系基向量(X、Y、Z轴单位向量)
original_axes = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
# 计算旋转后的基向量
rotated_axes = original_axes @ rotation_matrix.T

# 初始化3D绘图
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlabel('X轴')
ax.set_ylabel('Y轴')
ax.set_zlabel('Z轴')
ax.set_xlim(-3, 3)
ax.set_ylim(-3, 3)
ax.set_zlim(-1, 2)

# 绘制原坐标系箭头(红、绿、蓝对应X、Y、Z轴)
origin = (0, 0, 0)
colors = ['r', 'g', 'b']
labels = ['原X轴', '原Y轴', '原Z轴']
for axis, color, label in zip(original_axes, colors, labels):
    ax.quiver(*origin, *axis, color=color, arrow_length_ratio=0.1, label=label)

# 绘制旋转后的坐标系箭头(深色调区分)
rotated_colors = ['darkred', 'darkgreen', 'darkblue']
rotated_labels = ['旋转后X轴', '旋转后Y轴', '旋转后Z轴']
for axis, color, label in zip(rotated_axes, rotated_colors, rotated_labels):
    ax.quiver(*origin, *axis, color=color, arrow_length_ratio=0.1, label=label)

ax.legend()
plt.title('3D旋转变换坐标系可视化')
plt.show()

代码说明

  1. 将矩阵转为NumPy数组,方便进行矩阵乘法运算
  2. 提取旋转矩阵的前3行3列,用于变换坐标系基向量
  3. 使用quiver函数绘制带箭头的坐标轴,通过arrow_length_ratio调整箭头大小
  4. 设置合适的坐标轴范围,确保所有箭头完整显示
  5. 用不同颜色区分原始坐标系和旋转后的坐标系,直观对比旋转效果

内容的提问来源于stack exchange,提问作者mystic.06

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 04:23:12