.. note::
    :class: sphx-glr-download-link-note

    Click :ref:`here <sphx_glr_download_gallery_animation_animate_decay.py>` to download the full example code
.. rst-class:: sphx-glr-example-title

.. _sphx_glr_gallery_animation_animate_decay.py:


=====
Decay
=====

This example showcases:
- using a generator to drive an animation,
- changing axes limits during an animation.




.. image:: /gallery/animation/images/sphx_glr_animate_decay_001.png
    :class: sphx-glr-single-img





.. code-block:: python


    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation


    def data_gen(t=0):
        cnt = 0
        while cnt < 1000:
            cnt += 1
            t += 0.1
            yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)


    def init():
        ax.set_ylim(-1.1, 1.1)
        ax.set_xlim(0, 10)
        del xdata[:]
        del ydata[:]
        line.set_data(xdata, ydata)
        return line,

    fig, ax = plt.subplots()
    line, = ax.plot([], [], lw=2)
    ax.grid()
    xdata, ydata = [], []


    def run(data):
        # update the data
        t, y = data
        xdata.append(t)
        ydata.append(y)
        xmin, xmax = ax.get_xlim()

        if t >= xmax:
            ax.set_xlim(xmin, 2*xmax)
            ax.figure.canvas.draw()
        line.set_data(xdata, ydata)

        return line,

    ani = animation.FuncAnimation(fig, run, data_gen, blit=False, interval=10,
                                  repeat=False, init_func=init)
    plt.show()


.. _sphx_glr_download_gallery_animation_animate_decay.py:


.. only :: html

 .. container:: sphx-glr-footer
    :class: sphx-glr-footer-example



  .. container:: sphx-glr-download

     :download:`Download Python source code: animate_decay.py <animate_decay.py>`



  .. container:: sphx-glr-download

     :download:`Download Jupyter notebook: animate_decay.ipynb <animate_decay.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    Keywords: matplotlib code example, codex, python plot, pyplot
    `Gallery generated by Sphinx-Gallery
    <https://sphinx-gallery.readthedocs.io>`_
