我已经完成了 2 个立方体的 3D 图。但是现在我想让它旋转,那么我怎样才能旋转里面的立方体呢?我想水平旋转 90º 度!
这是代码:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("auto")
ax.set_autoscale_on(True)
#dibujar cubo
r = [-10, 10]
for s, e in combinations(np.array(list(product(r,r,r))), 2):
if np.sum(np.abs(s-e)) == r[1]-r[0]:
ax.plot3D(*zip(s,e), color="b")
#dibujar punto
#ax.scatter([0],[0],[0],color="g",s=100)
d = [-2, 2]
for s, e in combinations(np.array(list(product(d,d,d))), 2):
if np.sum(np.abs(s-e)) == d[1]-d[0]:
ax.plot3D(*zip(s,e), color="g")
plt.show()
请您参考如下方法:
当您单独绘制每个顶点时,我认为您需要对每个顶点应用旋转。 3D 旋转可能会令人困惑,有多种方法可以定义这种旋转,并且取决于您想要旋转的方式,这将取决于您将选择哪种旋转。
你说你想水平旋转它,在这样的 3d 图片中不清楚这是什么意思所以如果我错误地假设你想旋转它请原谅我说z 轴一个角度 theta。
要旋转长度为 3 的向量 p,我们保持第三个分量不变,并对其他两个分量应用旋转。这最好通过矩阵乘法来理解,但我会将解释留给 Wolfram pages :
p_rotated_x = p_x * sin(theta) - p_y * sin(theta)
p_rotated_y = p_x * sin(theta) + p_y * cos(theta)
p_rotate_z = p_z
这是应用上面链接中的 R_z 旋转矩阵后的旋转分量。在导入一些三角函数后将其应用于您的代码
from numpy import sin, cos
theta = np.radians(30)
for s, e in combinations(np.array(list(product(d,d,d))), 2):
if np.sum(np.abs(s-e)) == d[1]-d[0]:
s_rotated = [s[0] * cos(theta) - s[1] * sin(theta),
s[0] * sin(theta) + s[1] * cos(theta),
s[2]]
e_rotated = [e[0] * cos(theta) - e[1] * sin(theta),
e[0] * sin(theta) + e[1] * cos(theta),
e[2]]
ax.plot3D(*zip(s_rotated,e_rotated), color="g")
plt.show()
这给出:
请注意,三角函数以度为单位指定角度,需要以弧度为单位(因此进行转换)。
这是一个非常简单的轮换,实现起来也有些简单。我承认这可以改进,但基本思想就在那里。如果你想用更复杂的方法旋转它,我建议阅读 Euler angles这是一种(至少对我而言)理解 3d 旋转的直观方式。
