2013-08-20 302 views
15

我有一個散點圖設置和繪製我想要的方式,我想創建一個.mp4視頻的空間旋轉圖,就好像我已經使用了plt.show()並拖動了周圍的觀點。在matplotlib中動畫旋轉3D圖形

This answer幾乎正是我想要的,除了保存電影,我將不得不手動調用FFMpeg與圖像文件夾。我寧願使用Matplotlib內置的動畫支持,而不是保存單個幀。代碼轉載如下:

from mpl_toolkits.mplot3d import Axes3D 
ax = Axes3D(fig) 
ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6) 
for ii in xrange(0,360,1): 
    ax.view_init(elev=10., azim=ii) 
    savefig("movie"%ii+".png") 
+0

工作完美,謝謝! – Nate

回答

20

如果您想了解更多關於matplotlib動畫你真的應該遵循this tutorial。它詳細解釋瞭如何創建動畫圖。

注意:創建動畫圖要求安裝ffmpegmencoder

這是他的第一個例子的一個版本,改爲與你的散點圖一起工作。

# First import everthing you need 
import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib import animation 
from mpl_toolkits.mplot3d import Axes3D 

# Create some random data, I took this piece from here: 
# http://matplotlib.org/mpl_examples/mplot3d/scatter3d_demo.py 
def randrange(n, vmin, vmax): 
    return (vmax - vmin) * np.random.rand(n) + vmin 
n = 100 
xx = randrange(n, 23, 32) 
yy = randrange(n, 0, 100) 
zz = randrange(n, -50, -25) 

# Create a figure and a 3D Axes 
fig = plt.figure() 
ax = Axes3D(fig) 

# Create an init function and the animate functions. 
# Both are explained in the tutorial. Since we are changing 
# the the elevation and azimuth and no objects are really 
# changed on the plot we don't have to return anything from 
# the init and animate function. (return value is explained 
# in the tutorial. 
def init(): 
    ax.scatter(xx, yy, zz, marker='o', s=20, c="goldenrod", alpha=0.6) 
    return fig, 

def animate(i): 
    ax.view_init(elev=10., azim=i) 
    return fig, 

# Animate 
anim = animation.FuncAnimation(fig, animate, init_func=init, 
           frames=360, interval=20, blit=True) 
# Save 
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264']) 
+1

對不起,我希望你沒有被冒犯。不確定我是否同意你缺乏回報價值。我認爲'blit'需要它們正常工作,但圖書館的那一部分對我來說仍然是一個黑盒子。 (我做了答案投票)。 – tacaswell

+1

當然你還沒有! :D我非常尊重你的評論,因爲他們來自一位經驗豐富的matplotlib開發人員!我試圖向他們學習,並根據你的建議行事(昨天關於問題標記)。所以,請**每當你認爲我做錯了某件事時,請糾正我的錯誤:)。這既符合SO社區的利益,也符合我自己的學習過程。剛剛發生的是,我們在前一個問題上存在輕微的方法論分歧,所以我將其作爲一個笑話加入,因爲我知道您會讀取所有'matplotlib'問題:) –

+0

關於返回值。在博客文章中,傑克說:「這個函數返回線對象是很重要的,因爲這告訴動畫師在每一幀之後更新圖上的哪些對象。」但是由於情節中沒有任何物體發生變化,我認爲不應該返回任何東西。如果這是不正確的假設,我將編輯帖子。 –