Putting limits on a matplotlib animation with plt.ion()

778 Views Asked by At

I'm trying to make an animation with matplotlib without using FuncAnimation, because it's causing problems with the HTML (ffmpeg). I'm now trying with the plt.ion() which is more often used for live plot.

I had no problems making the animation, but the curve isn't really moving, it's the boundaries that are moving most of the time.

I tried the usual boundaries, like set plt.xlim(#boundaries) and for the y... but it didn't work. Any clues on how to fix the problem?

Here is what I have done (it's just example code, because the animation that I want to do is the quantum wave function and that code is already kinda messy)

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

a = int(input("render level = "))
tmax = float(input("tmax = "))

x = np.linspace(0, 2*np.pi, a)
t = np.linspace(0, tmax, a)

plt.figure()
plt.ion()
plt.xlim([0, 2*np.pi])
plt.ylim([-1.2, 1.2])
plt.plot([], [])

i = 0


while i<a:
    y = np.cos(t[i])*np.sin(x)
    print(t[i])

    plt.clf()
    plt.plot(x, y)
    plt.pause(1/(a*tmax))
    i = i + 1
1

There are 1 best solutions below

1
On BEST ANSWER

It' not plotting just the boundaries. It gives that impression because the y axis limits are self-adjusting all the time. This is because you are clearing the figure n the while loop, and with it it forgets whatever you had set before.

So you have to repeat the axes limits n the while loop. Try writing your while loop like so:

while i<a:
    y = np.cos(t[i])*np.sin(x)
    print(t[i])

    plt.clf()
    plt.plot(x, y)
    plt.xlim([0, 2*np.pi])
    plt.ylim([-1.2, 1.2])
    plt.title('Time is {}'.format(i))
    plt.pause(1/(a*tmax))

    i = i + 1

enter image description here