极简教程: 使用 matplotlib 绘制 GIF 动图

栏目: Python · 发布时间: 6年前

内容简介:12 February 2019开门见山,直接上例子:

12 February 2019

开门见山,直接上例子:

极简教程: 使用 matplotlib 绘制 GIF 动图

有如下特点:

  1. 散点图的部分是不变的;线是移动的
  2. X 轴标题每一祯改变一次

DEMO 的环境

  • Ubuntu 18.04.2 LTS
  • conda 4.6.3
  • Python 3.7.2

创建 virtualenv

ichexw at n3xt-Studio -> conda create --name matplot-gif python=3.7
ichexw at n3xt-Studio -> conda activate matplot-gif

安装必要的依赖

安装 matplotlib

(matplotlib-gif) ichexw at n3xt-Studio -> conda install matplotlib

安装 imagemagick

(matplotlib-gif) ichexw at n3xt-Studio -> conda install -c conda-forge imagemagick

代码实现

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

# 创建图层和布局
fig, ax = plt.subplots()
fig.set_tight_layout(True)

# 查看图标的尺寸。如果你保存成 gif 的时候,你需要提供 DPI
print('fig size: {0} DPI, size in inches {1}'.format(
    fig.get_dpi(), fig.get_size_inches()))

# 绘制一个散点图(不会重绘),和初始的线
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)
    
    # 更新线和坐标轴标签
    line.set_ydata(x - 5 + i)
    ax.set_xlabel(label)
    
    # 返回要重绘的对象
    return line, ax

if __name__ == '__main__':
    # FunAnimation 将会在每一帧执行一次 update
    # frames: 帧数
    # interval: 每帧的间隔
    anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)
	if len(sys.argv) > 1 and sys.argv[1] == 'save':
        # 如果第一参数是 save,教会保存成 gif
        # **重点**
        # dpi: 保存的尺寸
        # writer: 使用的渲染器,我们制定成 imagemagick
        anim.save('line.gif', dpi=80, writer='imagemagick')
    else:
        # 否则直接展示
        plt.show()

以上所述就是小编给大家介绍的《极简教程: 使用 matplotlib 绘制 GIF 动图》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

XML Hacks

XML Hacks

Michael Fitzgerald / O'Reilly Media, Inc. / 2004-07-27 / USD 24.95

Developers and system administrators alike are uncovering the true power of XML, the Extensible Markup Language that enables data to be sent over the Internet from one computer platform to another or ......一起来看看 《XML Hacks》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试