我需要在 matplotlib 中转换 3D 图形。我尝试使用 FuncAnimation(),但是,就我而言,这个东西仅在图形扩大或缩小而不是旋转时有用。然后我尝试了结构
for angle in range(0, 360):
ax.view_init(10, angle)
plt.draw()
plt.pause(.001)
问题是,暂停()函数是实验性的,不能以任何给定的速度旋转图形。
您可以使用以下方法:
%matplotlib notebook
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
vertices = [
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1]
]
edges = [
(0, 1), (1, 2), (2, 3), (3, 0),
(4, 5), (5, 6), (6, 7), (7, 4),
(0, 4), (1, 5), (2, 6), (3, 7)
]
# Plotting
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for angle in range(0,181,10): # for angles, 0,10,20...,180
ax.cla() # important to clear ax only, not fig
for vertex in vertices: # scatter the nodes
ax.scatter(vertex[0], vertex[1], vertex[2], color='r')
for edge in edges: # plot the edges as lines
ax.plot3D([vertices[edge[0]][0], vertices[edge[1]][0]],
[vertices[edge[0]][1], vertices[edge[1]][1]],
[vertices[edge[0]][2], vertices[edge[1]][2]], 'b')
# add labels
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# adjust the angle and update the plot, save fig for later
ax.view_init(30, angle)
ax.set_title("Rotation: "+str(angle)+"°")
fig.canvas.draw()
plt.savefig("rotation/"+str(angle).zfill(3)+".png")
我保存了图像并创建了动画: