Python Forum

Full Version: Matplotlib FuncAnimation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have a question about FuncAnimation of Matplotlib. Here is my code:

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


def update(n):
    t = n * delta_t
    u = np.cos(k * x - omega * t)
    plot.set_ydata(u)
    text.set_text(f"t = {t:5.1f}")

    return plot, text,


def init():
    global plot
    global text
    plot, = ax.plot(x, np.cos(k * x))
    text = ax.text(0.0, 1.05, '')

    return plot, text,


if __name__ == '__main__':
    x = np.linspace(0, 20, 500)
    omega = 1.0
    k = 1.0
    delta_t = 0.02

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.set_ylim(-1.2, 1.2)
    ax.set_xlabel("Ort x")
    ax.set_ylabel("u(x, t)")
    ax.grid()

    ani = mpl.animation.FuncAnimation(fig, update, interval=3000, blit=True, init_func=init)
    plt.show()
It start's without the line-plot. After 3s there is a line-plot. I don't know, why. I thought, it would start with the init() and after 3s it would call update().
Your interval is very long. Try this:
def init():
    global plot
    global text
    plot, = ax.plot(x, np.cos(k * x))
    text = ax.text(0.0, 1.05, '')

    return plot, text,


if __name__ == '__main__':
    x = np.linspace(0, 20, 500)
    omega = 1.0
    k = 1.0
    delta_t = 0.02

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.set_ylim(-1.2, 1.2)
    ax.set_xlabel("Ort x")
    ax.set_ylabel("u(x, t)")
    ax.grid()

    ani = mpl.animation.FuncAnimation(fig, update, interval=50, blit=True, init_func=init)
    plt.show()
Hey,

I know, that my interval is very long. I did it on purpose to see how the diagram starts.

I didn't expect, that it start's without the line-plot. I think, I don't understand the FuncAnimation :D :D
It does what I want, if I say blit=False. But why?