Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll backwards and forwards through matplotlib plots

My code produces a number of plots from data using matplotib and I would like to be able to scroll forwards and backwards through them in a live demonstration (maybe by pressing the forwards and backwards keys or using the mouse). Currently I have to save each one as an image separately and then use a separate image viewer to scroll through them. Is there any way of doing this entirely from within python?

like image 416
graffe Avatar asked Aug 22 '13 20:08

graffe


1 Answers

An easy way to achieve that is storing in a list a tuple of the x and y arrays and then use a handler event that picks the next (x,y) pair to be plotted:

import numpy as np
import matplotlib.pyplot as plt

# define your x and y arrays to be plotted
t = np.linspace(start=0, stop=2*np.pi, num=100)
y1 = np.cos(t)
y2 = np.sin(t)
y3 = np.tan(t)
plots = [(t,y1), (t,y2), (t,y3)]

# now the real code :) 
curr_pos = 0

def key_event(e):
    global curr_pos

    if e.key == "right":
        curr_pos = curr_pos + 1
    elif e.key == "left":
        curr_pos = curr_pos - 1
    else:
        return
    curr_pos = curr_pos % len(plots)

    ax.cla()
    ax.plot(plots[curr_pos][0], plots[curr_pos][1])
    fig.canvas.draw()

fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', key_event)
ax = fig.add_subplot(111)
ax.plot(t,y1)
plt.show()

In this code I choose the right and left arrows to iterate, but you can change them.

like image 67
jabaldonedo Avatar answered Sep 20 '22 19:09

jabaldonedo