Victor José
Victor José

Reputation: 387

Plot a graph, clear its axes, then plot a new graph

I'm trying to do the following: create a figure, plot a graph on it, then in 3 seconds clear its axes. When that happen a new graph should be plotted on the same figure and it should be updated on the screen.

Something like:

import matplotlib.pyplot as plt
import time

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3],[1,2,3])
plt.show()
time.sleep(3)
plt.ion()
plt.cla()
ax.plot([10,20,30],[10,20,30])
fig.canvas.draw()

But it isn't working. What's wrong with this logic?

Upvotes: 0

Views: 415

Answers (1)

DarthSpeedious
DarthSpeedious

Reputation: 1007

If you want to animate your figures, you can use matplotlib.animation library. Here is what your code would look like:

import matplotlib.pyplot as plt
import time
import matplotlib.animation as animation

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([],[])
ax.set_xlim(3)
ax.set_ylim(3)
line.set_data([1,2,3],[1,2,3])

def init():
            """ Initializes the plots to have zero values."""
            line.set_data([],[])
            return line,

def animate(n, *args, **kwargs):
    if(n%2==0):
        line.set_data([],[])
    else:   
        line.set_data([1,2,3],[1,2,3])

    return line,

ani = animation.FuncAnimation(fig, animate, init_func=init,frames =100, interval=10, blit=False, repeat =False)
fig.show()

Look into matplotlib.animation for more details. This link can get you started.

Upvotes: 1

Related Questions