代码之家  ›  专栏  ›  技术社区  ›  Frank

时间相关绘图matplotlib

  •  1
  • Frank  · 技术社区  · 7 年前

    我想通过Matplotlib在Python中逐点绘制一个正弦波,每个点都是在 十、 毫秒,以获得图形的平滑动画。

    这是我的尝试:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    from math import sin
    
    fig, ax = plt.subplots()
    
    x = [0]
    line, = ax.plot(x, np.asarray(0))
    
    
    def animate(i):
        x.append(x[-1]+0.04)
        line.set_xdata(np.asarray(x)*2*np.pi/5)
        line.set_ydata(np.sin(np.asarray(x)*2*np.pi/5))
        plt.draw()
    
    def init():
        line.set_ydata(np.ma.array(x, mask=True))
        return line,
    
    ani = animation.FuncAnimation(fig, animate, 10, init_func=init, interval=40, blit=True)
    
    plt.show()
    

    这引发了:

    RuntimeError: The animation function must return a sequence of Artist objects.
    

    我弄错了什么?在你看来,获得这种效果的最有效方法是什么?

    PS时间轴应保持固定且不移动,因此应比绘图宽

    2 回复  |  直到 7 年前
        1
  •  2
  •   Christoffer    7 年前

    首先,由于您的 animate(i) 没有返回任何内容。你需要回去 line, .其次,您没有使用 i 在里面 动画制作(i) 还有。

    下面是一个简单的正弦曲线动画 https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/ :

    import numpy as np
    from matplotlib import pyplot as plt
    from matplotlib import animation
    
    # First set up the figure, the axis, and the plot element we want to 
    animate
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
    line, = ax.plot([], [], lw=2)
    
    # initialization function: plot the background of each frame
    def init():
        line.set_data([], [])
        return line,
    
    # animation function.  This is called sequentially
    def animate(i):
        x = np.linspace(0, 2, 1000)
        y = np.sin(2 * np.pi * (x - 0.01 * i))
        line.set_data(x, y)
        return line,
    
    # call the animator.  blit=True means only re-draw the parts that have 
    changed.
    anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)
    
    plt.show()
    

    链接中还有其他灵感,可能会进一步帮助您。

        2
  •  1
  •   Dodge Sagar Bahadur Tamang    7 年前

    动画应返回艺术家对象的序列:

    您应该添加:

    return line, 到动画功能的末尾

    def animate(i):
        x.append(x[-1]+0.04)
        line.set_xdata(np.asarray(x)*2*np.pi/5)
        line.set_ydata(np.sin(np.asarray(x)*2*np.pi/5))
        return line,
    

    资料来源:

    Another answer

    Simple Example