【问题标题】:Updating Animation Label in Python在 Python 中更新动画标签
【发布时间】:2017-02-18 05:35:58
【问题描述】:

我有一个 Python 动画,我想添加一个更新的时间标签。我已经有一个名为 time 的 NumPy 数组,所以我认为它就像将变量插入标签一样简单。

fig, ax = plt.subplots()
line, = ax.plot([], lw=2)
time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)

plotlays, plotcols = [1], ["blue"]
lines = []
for index in range(1):
    lobj = ax.plot([], [], lw=2, color=plotcols[index])[0]
    lines.append(lobj)

def animate(i):
    xlist = [xvals]
    ylist = [psisol[i,:].real]
    time_text.set_text('time = %0.2f' % time[i])

    for lnum, line in enumerate(lines):
        line.set_data(xlist[lnum], ylist[lnum])

    return lines

我从 Jake Vanderplas 的 Double Pendulum 教程 here 中获取它,我还查看了这个 StackOverflow post。程序执行时,绘图区域保持灰色。如果我注释掉文本代码,程序运行得非常好,并且可以绘制和动画。不知道还能尝试什么。

感谢您的帮助。

【问题讨论】:

    标签: python-2.7 animation matplotlib


    【解决方案1】:

    我编辑了您从中获取的教程,在图表中添加了动画文本。下次请提供可重现的代码(xvals是什么?psisol?+没有导入)

    """
    Matplotlib Animation Example
    
    author: Jake Vanderplas
    email: vanderplas@astro.washington.edu
    website: http://jakevdp.github.com
    license: BSD
    Please feel free to use and modify this, but keep the above information. Thanks!
    """
    
    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)
    time_text = ax.text(0.02, 0.95, '', transform=ax.transAxes)
    
    # initialization function: plot the background of each frame
    def init():
        line.set_data([], [])
        time_text.set_text('')
        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)
        time_text.set_text(str(i))
        return tuple([line]) + tuple([time_text])
    
    # 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多