2017-04-03 1088 views
0

我有這段代碼,其中包含一個3D圖。我在Spyder中運行代碼;我想知道是否可以使這個繪圖旋轉(360度)並保存。 謝謝! P.s.對不起,如果這是一個愚蠢的問題,但我是Python的newby。如何在python中旋轉3d圖? (或作爲動畫)使用鼠標旋轉三維視圖

import matplotlib.pyplot as plt 
import numpy as np 
from scipy import array 
jet = plt.get_cmap('jet') 
from matplotlib import animation 
fig = plt.figure() 
ax = fig.gca(projection='3d') 

X = np.linspace(70,40,4) 
Y = np.linspace(5,2,4) 
X,Y= np.meshgrid(X, Y) 

Z = array ([ 
     [1223.539555, 1428.075086,1714.479425, 2144.053223], 
     [1567.26647,1829.056119,2990.416079,2745.320067], 
     [2135.163957,2491.534201, 2990.416079,3738.761638], 
     [3257.280827, 3800.655101, 4561.372117, 5702.458776], 
     ]) 

surf = ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = jet,linewidth = 0,alpha= 1) 
ax.set_zlim3d(0, Z.max()) 

fig.colorbar(surf, shrink=0.8, aspect=5) 
ax.set_xlabel('Axial Length [mm]') 
ax.set_ylabel('nbTurns') 
ax.set_zlabel('RPM') 

plt.show() 

回答

2

您需要定義一個函數以獲取特定的動畫。在你的情況下,它是一個簡單的旋轉:

def rotate(angle): 
    ax.view_init(azim=angle) 

然後使用matplotlib動畫:

rot_animation = animation.FuncAnimation(fig, rotate, frames=np.arange(0,362,2),interval=100) 

這將調用與frames參數作爲角度和與100ms的間隔旋轉功能,所以這將導致360°的輪換,其中步驟每個100ms。將動畫保存爲gif文件:

rot_animation.save('path/rotation.gif', dpi=80, writer='imagemagick') 
+0

嗨,首先我要感謝您的幫助和解答。我修改了我的初始代碼,但仍然覺得我的保存部分有問題。運行後,出現此錯誤** renderer._renderer.write_rgba(filename_or_obj) RuntimeError:寫入文件**的錯誤** –

+0

這似乎是一個常見問題(請參閱http://stackoverflow.com/questions/25140952/matplotlib - 保存動畫功能於GIF錯誤)。確保'imagemagick'安裝正確,否則你也可以嘗試將它保存爲mp4格式,如上面的鏈接所示。 –