在matplotlib中设置旋转三维图形的动画

2024-05-13 01:22:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经建立了一个散点图,并按照我想要的方式绘制,我想创建一个图形在空间中旋转的.mp4视频,就像我使用了plt.show()并拖动了视点一样。

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")

Tags: answer图形视频电影show方式绘制空间
3条回答

当我无意中发现这一点时,我正在研究用matplotlib制作我的绘图动画: http://zulko.wordpress.com/2012/09/29/animate-your-3d-plots-with-pythons-matplotlib/

它提供了一个简单的函数,可以围绕一个绘图设置动画,并以多种格式输出。

如果你想了解更多关于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'])

这有点麻烦,但是如果你使用的是Jupyter笔记本,你可以使用cell magics直接从笔记本上运行ffmpeg的命令行版本。在一个单元格中运行脚本以生成原始帧

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%d.png" % ii)

现在,在新的笔记本单元格中,输入以下内容,然后运行单元格

%%bash 
ffmpeg -r 30 -i movie%d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4

相关问题 更多 >