在 matplotlib 中为旋转 3D 图形设置动画 [英] Animate a rotating 3D graph in matplotlib

查看:32
本文介绍了在 matplotlib 中为旋转 3D 图形设置动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a scatter plot set up and plotted the way I want it, and I want to create an .mp4 video of the figure rotating in space, as if I had used plt.show() and dragged the viewpoint around.

这个答案几乎正是我想要的,除了保存一部电影我必须手动调用 FFMpeg一个图像文件夹.我宁愿使用 Matplotlib 的内置动画支持,而不是保存单个帧.代码转载如下:

This answer is almost exactly what I want, except to save a movie I would have to manually call into FFMpeg with a folder of images. Instead of saving individual frames I'd prefer to use Matplotlib's built in animation support. Code reproduced below:

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

推荐答案

如果您想了解有关 matplotlib 动画的更多信息,您应该真正关注 本教程.它详细解释了如何创建动画情节.

If you want to learn more about matplotlib animations you should really follow this tutorial. It explains in great length how to create animated plots.

注意:创建动画图需要安装 ffmpegmencoder.

Note: Creating animated plots require ffmpeg or mencoder to be installed.

这是他的第一个示例的一个版本,已更改为适用于您的散点图.

Here is a version of his first example changed to work with your scatterplot.

# 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'])

这篇关于在 matplotlib 中为旋转 3D 图形设置动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆