zoukankan      html  css  js  c++  java
  • 『Python』matplotlib实现动画效果

    一般而言,在绘制复杂动画时,主要借助模块animation来完成

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from matplotlib.animation import FuncAnimation
    
    # mpl.use("Qt5Agg")
    
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    mpl.rcParams['font.serif'] = ['SimHei']
    mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串
    
    fig, ax = plt.subplots(1, 1)
    
    x = np.linspace(0, 2 * np.pi, 5000)
    y = np.exp(-x) * np.cos(2 * np.pi * x)
    line, = ax.plot(x, y, color="cornflowerblue", lw=3)
    ax.set_ylim(-1.0, 1.0)
    
    
    # to clear current frame
    def init():
        line.set_ydata([np.nan] * len(x))
        return line,
    
    
    # to update the data
    def animate(data):
        line.set_ydata(np.exp(-x) * np.cos(2 * np.pi * x + float(data) / 100))
        return line,
    
    
    # to call class FuncAnimation which connects animate and init
    ani = FuncAnimation(fig, animate, init_func=init, frames=200, interval=2, blit=True)
    
    # to save the animation
    ani.save("movie.mp4", fps=20, writer="ffmpeg")
    
    plt.show()
    

    下面展示其中的4帧结果

    • line,中的逗号是不能省略的,不然就不是Line2D对象了

    • FuncAnimation的构造函数主要的参数有Figure对象、函数func、帧数frames,帧时间间隔interval

  • 相关阅读:
    无符号数和有符号数之间赋值和大小比较
    (转)关于Linux核心转储文件 core dump
    mysql忘记root密码解决办法
    CentOS7安装iptables防火墙
    CENTOS7下安装REDIS
    iptables命令(备忘)
    ps 命令详解
    virtualenv
    How to Baskup and Restore a MySQL database
    linux 用户/用户组添加修改删除(ubuntu/centos)
  • 原文地址:https://www.cnblogs.com/ice-coder/p/12908708.html
Copyright © 2011-2022 走看看