Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib, step by step animation

Tags:

matplotlib

It's a pretty basic question on matplotlib, but I cannot figure out how to do it :

I want to plot multiple figures and use the arrow in the plot window to move from one to another.

for the time being I just know how to create mutiple plots and plot them in different windows like this :

import matplotlib.pyplot as plt

fig = plt.figure()
plt.figure(1)
n= plt.bar([1,2,3,4],[1,2,3,4])
plt.figure(2)
n= plt.bar([1,2,3,4],[-1,-2,-3,-4])
plt.show() 

or having multiple figures on the same window using subplot.

How can I have mutliple plots on the same window and move from one to the next one with the arrows ?

Thanks in advance.

like image 980
Ricky Bobby Avatar asked Jun 18 '12 17:06

Ricky Bobby


People also ask

How do I show an animation in Matplotlib?

Animations in Matplotlib can be made by using the Animation class in two ways: By calling a function over and over: It uses a predefined function which when ran again and again creates an animation. By using fixed objects: Some animated artistic objects when combined with others yield an animation scene.


1 Answers

To produce a plot which is updated as you press the left and right keys, you will need to handle keyboard events (docs: http://matplotlib.sourceforge.net/users/event_handling.html).

I have put together an example of updating a plot, using the pyplot interface, when you press the left and right arrows:

import matplotlib.pyplot as plt
import numpy as np


data = np.linspace(1, 100)
power = 0
plt.plot(data**power)


def on_keyboard(event):
    global power
    if event.key == 'right':
        power += 1
    elif event.key == 'left':
        power -= 1

    plt.clf()
    plt.plot(data**power)
    plt.draw()

plt.gcf().canvas.mpl_connect('key_press_event', on_keyboard)

plt.show()
like image 85
pelson Avatar answered Sep 24 '22 05:09

pelson