用Matplotlib制作动画

624 阅读1分钟

欢迎关注公众号 数据分析那些事儿

1 先上菜

2 动态图表应该怎么画呢

直接上代码

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd

fig, ax = plt.subplots()
x,y = [], []
line, =ax.plot(x,y,'g-', animated=True)

def init():
    x.clear()
    y.clear()
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return line,

def update(i):
    x.append(i)
    y.append(np.sin(i))
    line.set_data(x,y)
    return line,

ani = FuncAnimation(fig,update,frames=np.linspace(0, 2*np.pi, 128),init_func=init,blit=True)
plt.show()

3 FuncAnimation函数介绍

class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs)

fig : matplotlib.figure.Figure
func : callable
frames : iterable, int, generator function, or None, optional
init_func : callable, optional
fargs : tuple or None, optional
interval : number, optional

repeat_delay : number, optional
repeat : bool, optional

4 保存为视频

ani.save('sin.mp4')

5 moviewriter ffmpeg unavailable怎么处理

很多同学会遇到moviewriter ffmpeg unavailable这个问题,主要是系统没有安装ffmpeg
ffmpeg下载地址
注意直接下载编译好的static版本

针对macos、linux

1、解压缩后随便放在一个目录
2、配置环境变量

vi ~/.bash_profile

添加环境变量,例如/Users/summer/ffmpeg/bin
然后source一下,让环境变量生效

source ~/.bash_profile

3、测试一下

localhost:~$ ffmpeg
ffmpeg version git-2020-04-17-889ad93 Copyright (c) 2000-2020 the FFmpeg developers
  built with Apple clang version 11.0.0 (clang-1100.0.33.8)
  configuration: --enable-gpl --enable-version3 --enable-sdl2 --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libdav1d --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libsrt --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-appkit --enable-avfoundation --enable-coreimage --enable-audiotoolbox
  libavutil      56. 42.102 / 56. 42.102
  libavcodec     58. 80.100 / 58. 80.100
  libavformat    58. 42.100 / 58. 42.100
  libavdevice    58.  9.103 / 58.  9.103
  libavfilter     7. 77.101 /  7. 77.101
  libswscale      5.  6.101 /  5.  6.101
  libswresample   3.  6.100 /  3.  6.100
  libpostproc    55.  6.100 / 55.  6.100

安装成功! 然后在重新运行程序,视频搞定!