• Matplotlib绘制动图以及绘制平滑曲线


    绘制动图

    在这里插入图片描述
    FuncAnimation,它的使用要求简洁且定制化程度较高。如果想将很多图片合并为一个动图,那么ArtistAnimation是最合适的选择。

    FuncAnimation

    通过反复调用同一函数来制作动画。
    注意:创建FuncAnimation对象后一定要将其赋值给某个变量,否则系统会将其进行垃圾回收。

    class matplotlib.animation.FuncAnimation(fig, 
    										func, 
    										frames=None, 
    										init_func=None, 
    										fargs=None, 
    										save_count=None, *, 
    										cache_frame_data=True, 
    										**kwargs)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    参数:

    • fig:Figure。用于显示动画的figure对象
    • func:callable。用于更新每帧动画的函数。func函数的第一个参数为帧序号。返回被更新后的图形对象列表。
    • frames:iterable, int, generator function, or None, optional。动画长度,帧序号组成的列表
    • init_func:callable, optional。自定义开始帧,即绘制初始化图形的初始化函数
    • fargs:tuple or None, optional。额外的需要传递给func函数的参数。
    • save_count:int, default: 100。保存计数
    • cache_frame_data:bool, default: True
    • interval:int, default: 200。重复调用功能函数的间隔时间,单位是毫秒。
    • repeat_delay:int, default: 0。当repeat为True时,动画延迟多少毫秒再循环。
    • repeat:bool, default: True。是否是循环动画。
    • blit:bool, default: False。选择更新所有点,还是仅更新产生变化的点。

    示例:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    fig = plt.figure()
    ax = fig.subplots()
    
    t=np.linspace(0,10,100)
    y=np.sin(t)
    ax.set_aspect(3)
    ax.plot(t,y,'--',c='gray')
    line=ax.plot(t,y,c='C2')
    
    def update(i):  #帧更新函数
        global t    #直接引用全局变量,也可以通过函数的frames或fargs参数传递。
        t+=0.1
        y=np.sin(t)
        line[0].set_ydata(y)
        return line
    
    ani=FuncAnimation(fig,update,interval=100) #绘制动画
    plt.show() #显示动画
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    fig = plt.figure(figsize=(7, 2), dpi=100)
    ax = plt.subplot()
    X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
    C, S = np.cos(X), np.sin(X)
    line1, = ax.plot(X, C, marker="o", markevery=[-1], markeredgecolor="white")
    line2, = ax.plot(X, S, marker="o", markevery=[-1], markeredgecolor="white")
    
    def update(frame):
        line1.set_data(X[:frame], C[:frame])
        line2.set_data(X[:frame], S[:frame])
    
    ani = animation.FuncAnimation(fig, update, interval=10)
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    方法

    1. init(fig, func[, frames, init_func, …])
    2. new_frame_seq()
    3. new_saved_frame_seq()
    4. pause()
    5. resume()
    6. save(self, filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None)
    • filename:保存的文件名
    • writer:FFMpegFileWriter,ImageMagickFileWriter, AVConvFileWriter对象实例,或者表示这些对象的字符串(‘ffmpeg’, ‘imagemagick’,‘avconv’)
    • fps:每秒的帧数
    1. to_jshtml([fps, embed_frames, default_mode])
      返回js动画,用base64文本编码。
    • fps:每秒帧数,默认根据动画的interval确定。
    • embed_frames:布尔类型,是否嵌入帧。
    • default_mode:‘loop’,‘once’或者’reflect’

    ArtistAnimation

    通过调用一个固定的Artist对象来制作动画,例如给定的系列图片或者matplotlib的绘图对象.。

    class matplotlib.animation.ArtistAnimation(fig, artists, *args, **kwargs)
    
    • 1

    参数:

    • fig:Figure
    • artists:list
    • interval:int, default: 200。每一帧之间的间隔
    • repeat_delay:int, default: 0。每显示一次动画后间隔多长时间重复
    • repeat:bool, default: True。是否重复动画
    • blit:bool, default: False

    示例:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.animation import ArtistAnimation
    fig = plt.figure()
    ax = fig.subplots()
    
    arts=[]
    t=np.linspace(0,np.pi*2,20)
    for i in range(20):
        t+=np.pi*2/20
        y=np.sin(t)
        lines=ax.plot(y,'--',c='gray')  #绘制一帧图形
        arts.append(lines)              #每帧图形都保存到列表中
    
    ani=ArtistAnimation(fig,arts,interval=200) #绘制动画
    #ani.save("animate_artists_basic.gif")  #保存动画
    plt.show() #显示动画
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述

    方法

    __init__(fig, artists, *args, **kwargs)
    
    • 1
    new_frame_seq()
    
    • 1
    new_saved_frame_seq()
    
    • 1
    pause()
    
    • 1
    resume()
    
    • 1
    save(filename[, writer, fps, dpi, codec, ...])
    
    • 1

    参数:

    • filename:保存的动画文件名称,如’mov.gif’,‘mov.mp4’。
    • writer:保持动画的库。MoviewWriter对象或者字符串。默认值’ffmpeg’。
      “pillow”:PillowWriter,用pillow库写如动画文件。
      “ffmpeg”:FFMpegWriter,‎基于ffmpeg库写动画。
      “ffmpeg_file”:FFMpegFileWriter,基于文件的FFMpegWriter,用ffmpeg库把帧写入临时文件,然后拼接成动画。
      “imagemagick”:ImageMagickWriter,‎基于管道的动画GIF。‎帧通过管道传输到ImageMagick并写入文件。
      “imagemagick_file”:基于文件的imagemagick写动画。
      “hmtl”:HTMLWriter,基于javascript html的动画。
    • fps:每秒帧数,默认根据动画的interval确定
    • dpi:每英寸点数,默认和figure相同。可以控制动画大小尺寸。
    • codec:编码格式,默认’h264’
    to_html5_video([embed_limit])
    
    • 1
    • embed_limit:动画文件大小限制,单位为MB。默认为20MB,超出限制则不创建动画。

    绘制平滑曲线

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.array([1, 2, 3, 4, 5, 6, 7])
    y = np.array([100, 50, 25, 12.5, 6.25, 3.125, 1.5625])
    
    plt.plot(x, y)
    plt.title("Spline Curve")
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    在这里插入图片描述

    使用 scipy.ndimage.gaussian_filter1d() 高斯核类绘制平滑曲线

    import numpy as np
    import matplotlib.pyplot as plt 
    from scipy.ndimage import gaussian_filter1d
    
    x=np.array([1,2,3,4,5,6,7])
    y=np.array([100,50,25,12.5,6.25,3.125,1.5625])
    y_smoothed = gaussian_filter1d(y, sigma=5)
    
    plt.plot(x, y_smoothed)
    plt.title("Spline Curve Using the Gaussian Smoothing")
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.show()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    使用 scipy.interpolate.make_interp_spline() 样条插值类绘制平滑曲线

    import numpy as np
    from scipy.interpolate import make_interp_spline
    import matplotlib.pyplot as plt 
    
    x=np.array([1,2,3,4,5,6,7])
    y=np.array([100,50,25,12.5,6.25,3.125,1.5625])
    
    model=make_interp_spline(x, y)
    
    xs=np.linspace(1,7,500)
    ys=model(xs)
    
    plt.plot(xs, ys)
    plt.title("Smooth Spline Curve")
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.show()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述
    它通过使用 scipy.interpolate.make_interp_spline() 首先确定花键曲线的系数,绘制出一条平滑的花键曲线。我们用给定的数据来估计花样曲线的系数,然后用系数来确定间隔紧密的 x 值的 y 值,使曲线平滑。绘制曲线需要沿 X 轴 1 到 7 之间间隔相等的 500。

    使用 scipy.interpolate.interp1d 插值类绘制平滑曲线

    import numpy as np
    from scipy.interpolate import interp1d
    import matplotlib.pyplot as plt 
    
    x=np.array([1,2,3,4,5,6,7])
    y=np.array([100,50,25,12.5,6.25,3.125,1.5625])
    
    cubic_interploation_model=interp1d(x,y,kind="cubic")
    xs=np.linspace(1,7,500)
    ys=cubic_interploation_model(xs)
    
    plt.plot(xs, ys)
    plt.title("Spline Curve Using Cubic Interpolation")
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.show()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述
    绘制曲线时,需要在 X 轴上 1 和 7 之间取间隔相等的 500 个点。

    拟合曲线后绘制动图

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    from scipy.interpolate import interp1d
    
    fig = plt.figure(figsize=(7, 2), dpi=100)
    ax = plt.subplot()
    
    x = np.array([1, 2, 3, 4, 5, 6, 7])
    y = np.array([100, 50, 25, 12.5, 6.25, 3.125, 1.5625])
    cubic_interploation_model = interp1d(x, y, kind="cubic")
    xs = np.linspace(1, 7, 500)
    ys = cubic_interploation_model(xs)
    line3 = ax.plot(xs, ys)
    
    def update(frame):
        line3[0].set_data(xs[:frame], ys[:frame])
    
    
    ani = animation.FuncAnimation(fig, update, interval=10)
    plt.show()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
  • 相关阅读:
    调试 Mahony 滤波算法的思考 10
    Java 定时任务-最简单的3种实现方法
    30岁生日收到公司的生日礼物,一份裁员通知,有人从此一蹶不振,而我逆风翻盘,重获新生~
    MySQL的安装与配置
    YOLOv8训练自己的数据集,十秒学会!小白一文学会YOLOv8训练全过程!适应于小白
    鸿蒙HarmonyOS实战-工具安装和Helloworld案例
    python-opencv高级形态学处理—边缘—凸包
    Vue中使用Web Serial API连接串口,实现通信交互
    Web前端:前端vs后端vs全栈开发人员——有什么区别?
    Spark基础操作(一)
  • 原文地址:https://blog.csdn.net/weixin_43956958/article/details/125965017