Python Matplotlib绘制动图平滑曲线

2022-08-12 11:46:10
目录
绘制动图FuncAnimationArtistAnimation使用 scipy.ndimage.gaussian_filter1d() 高斯核类绘制平滑曲线使用 scipy.interpolate.make_interp_spline() 样条插值类绘制平滑曲线使用 scipy.interpolate.interp1d 插值类绘制平滑曲线拟合曲线后绘制动图

绘制动图

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)

参数:

    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: Trueinterval: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() #显示动画

    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()

    方法 init(fig, func[, frames, init_func, …])

      new_frame_seq()new_saved_frame_seq()pause()resume()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:每秒的帧数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)

          参数:

            fig:Figureartists:listinterval: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() #显示动画

            方法:

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

            参数:

              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])

                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()

                使用>
                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()

                使用>
                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()

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

                使用>
                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()

                绘制曲线时,需要在 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()

                到此这篇关于Python Matplotlib绘制动图平滑曲线的文章就介绍到这了,更多相关Python Matplotlib绘制平滑曲线内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!