Matplotlib借助ImageMagick或ffmpeg生成动图(.gif)或视频可能遇到的问题和解决方案

准备工做

首先保证要安装matplotlib。假如按照如下流程而且在网上寻求解答依然没能成功运行,可能在于matplotlib版本太旧致使。php

更新使用pip:pip install -U matplotlib或者使用conda:conda update conda或者conda update matplotlib.python

生成动图(.gif)
ImageMagick
先下载ImageMagick (http://www.imagemagick.org/script/download.php#windows)。
windows最好是下载其dynamic版本(好比ImageMagick-7.0.8-10-Q16-x64-dll.exe)。web

安装后,安装选项中会有安装ffmpeg等选项,建议全部选项都勾选。其中ffmpeg能够用于以后生成.mp4等,也能够单独下载和使用。windows

以后检查安装路径下是否有convert.exe,有的话就大致没问题,不然从新选择正确的版本下载。app

安装正确后,将安装文件所在路径加入到环境变量中(一般安装的时候就添加到环境变量中了)。dom

不推荐但也是解决方法:假如不想添加到环境变量中或者忘了,则能够参考这里的作法,在notebook或者IDE中打印出matplotlib.matplotlib_fname()所在位置,并修改xxx\Lib\site-packages\matplotlib\mpl-data\matplotlibrc文本文件,将其中animation.convert_path:解注释,并在以后添加convert.exe路径,例如animation.convert_path: ‘“C:\Program Files\ImageMagick-6.9.0-Q16\convert.exe”’.svg

对于Plot的动态效果显示,如果在PyCharm等IDE中,打开终端或者使用命令行模式(而不是直接点击run),才能够显示动画。如果在notebook中,能够在导包语句加入一条%matplotlib notebook,则能够在当前cell运行以后查看动画效果;若想在cell以外即图表窗口中显示,请将%matplotlib notebook改成%matplotlib后面什么都不接(表示使用默认图像引擎),而后重启当前的kernel,从新运行此cell便可。
动画查看,对于IDE如PyCharm,使用命令行模式打开终端运行当前程序,便可查看动画效果,不然是单张图片。这里给出一个简单的样例:函数

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

fig, ax = plt.subplots(dpi=72, figsize=(8,6))

x = np.arange(-2*np.pi, 2*np.pi, 0.01)
y = np.sin(x)

line,  = ax.plot(x, y)

def init():
    line.set_ydata(np.sin(x))
    return line

def animate(i):
    line.set_ydata(np.sin(x+i/10.0))
    return line

anim = animation.FuncAnimation(fig=fig, 
                                       func=animate,
                                       frames=100, # total 100 frames
                                       init_func=init,
                                       interval=20,# 20 frames per second
                                       blit=False)
anim.save('sinx.gif', writer='imagemagick')
plt.show()

若能生成以下图所示的动图则为正常,若不能请仔细核对上面的几点。动画

生成视频(.mp4等)
matplotlib生成的图表一样能够转换为视频。使用的是ffmpeg,能够到官网下载对应的版本,其中windows先点击Download而后点击页面中下的build去选择你电脑的版本,默认选择static就好了。ui

因为速度超慢,因此这里下载后我把它们放在了百度网盘 密码:jq86了,文件夹中还有上文的ImageMagick,须要者自取。

下载后将安装后文件路径添加到系统环境变量中,cmd中输入ffmpeg -version若显示出对应的版本则表示安装无误。

若安装了ImageMagick则生成视频只须要将上面代码的.gif改为.mp4便可,而后以终端/命令行模式运行。

如果单独安装的ffmpeg,则将animation.save(‘sinx.gif’, writer=‘imagemagick’)改成animation.save(‘sinx.mp4’, writer=‘ffmpeg’)或者animation.save(‘sinx.mp4’)默认ffmpeg就能生成.mp4动态图表,一样而后以终端/命令行模式运行。

另外提供官方示例代码:

import numpy as np
import matplotlib
# matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation


def update_line(num, data, line):
    line.set_data(data[..., :num])
    return line,

# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)


fig1 = plt.figure()

data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
                                   interval=50, blit=True)
line_ani.save('lines.mp4', writer=writer)

fig2 = plt.figure()

x = np.arange(-9, 10)
y = np.arange(-9, 10).reshape(-1, 1)
base = np.hypot(x, y)
ims = []
for add in np.arange(15):
    ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)),))

im_ani = animation.ArtistAnimation(fig2, ims, interval=50, repeat_delay=3000,
                                   blit=True)
im_ani.save('im.mp4', writer=writer)

在这里插入图片描述

动图的核心函数是matplotlib.animation.FuncAnimation,基本用法是:

anim = animation.funcanimation(fig, animate, init_func=init, frames=100, interval=20, blit=true)
# fig: 是咱们建立的画布
# animat: 是重点,是咱们每一个时刻要更新图形对象的函数,返回值和init_func相同
# init_func: 初始化函数,其返回值就是每次都要更新的对象,
# 告诉FuncAnimation在不一样时刻要更新哪些图形对象
# frames: 至关于时刻t,要模拟多少帧图画,不一样时刻的t至关于animat的参数
# interval: 刷新频率,毫秒
# blit: blit是一个很是重要的关键字,它告诉动画只重绘修改的部分,结合上面保存的时间,
# blit=true会使动画显示得会很是很是快


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation  # 动图的核心函数
import seaborn as sns  # 美化图形的一个绘图包

sns.set_style("whitegrid")  # 设置图形主图

# 建立画布
fig, ax = plt.subplots()
fig.set_tight_layout(True)

# 画出一个维持不变(不会被重画)的散点图和一开始的那条直线。
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
line, = ax.plot(x, x - 5, 'r-', linewidth=2)

def update(i):
    label = 'timestep {0}'.format(i)
    print(label)
    # 更新直线和x轴(用一个新的x轴的标签)。
    # 用元组(Tuple)的形式返回在这一帧要被从新绘图的物体
    line.set_ydata(x - 5 + i)  # 这里是重点,更新y轴的数据
    ax.set_xlabel(label)    # 这里是重点,更新x轴的标签
    return line, ax

# FuncAnimation 会在每一帧都调用“update” 函数。
# 在这里设置一个10帧的动画,每帧之间间隔200毫秒
anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)

在这里插入图片描述