2013-08-20 209 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

关于返回值。在博客文章中,杰克说:“这个函数返回线对象是很重要的,因为这告诉动画师在每一帧之后更新图上的哪些对象。”但是由于情节中没有任何物体发生变化,我认为不应该返回任何东西。如果这是不正确的假设,我将编辑帖子。 –