How to update subplots?

Viewed 199

I need to plot many plots, take a look at them and press either "y" or "n". I can't get matplotlib showing plots one-by-one in a loop. The loop must show me a plot, then I will press some button and it starts again. My code for now is:

def press_event(event):
    answer = event.key
    if answer=='y':
        pass
    sys.stdout.flush()
    print(answer)
    
files = os.listdir(folder)

fig, ax = plt.subplots(14,2, figsize=(10,30))
fig.canvas.mpl_connect('key_press_event', press_event)
for file in files:
    target = file
    data = pd.read_csv(folder + target)
    fig.suptitle(target, fontsize=30)
    r = 0
    for key in data:
        sample = data[key]
        ts = [sample[i+1] - sample[i] for i in range(len(sample)-1)]
        decs,ts,point = cusum(sample,10)
        ax[r,0].plot(sample)
        ax[r,0].axvline(point,color='red')
        ax[r,1].plot(decs)
        ax[r,1].axvline(point, color='red')
        r += 1
    plt.show()
    fig.canvas.draw()
    plt.waitforbuttonpress()
    plt.pause(0.1)
    fig.clear()

Now it shows me the first plot. I press a button and next window is blank and kernel crashes.

1 Answers

Here is an adaption from this gallery example, using plt.waitforbuttonpress()

Blocking call to interact with the figure. Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within timeout seconds. Negative values deactivate timeout.

The figure updates as long as you press a key, if you click with the mouse the loop breaks.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(5, 2)

for i in range(10):
    x = np.random.random((5, 2, 100))

    for r, xx in enumerate(x):
        ax[r, 0].plot(xx[0], 'ro')
        ax[r, 1].plot(xx[1], 'bx')

    plt.show()
    fig.canvas.draw()
    if plt.waitforbuttonpress():  # True for key, False for mouse
        for axx in ax.flat:
            axx.clear()
    else:
        break

Another possibility is to use key_press_event. For this you need to combine the plot update in a separate function and call it accordingly. In this example I use the left and right keys to toggle through the data.


import numpy as np
import matplotlib.pyplot as plt

n = 10
x = np.random.random((n, 5, 2, 100))
global i
i = 0

fig, ax = plt.subplots(5, 2)

def update(j):
    for axx in ax.flat:
        axx.clear()

    for r, xx in enumerate(x[j]):
        ax[r, 0].plot(xx[0], 'ro')
        ax[r, 1].plot(xx[1], 'bx')

def press_event(event):
    global i
    if event.key == 'left':
        i -= 1
    elif event.key == 'right':
        i += 1
    else:
        return
    i %= n
    update(i)

fig.canvas.mpl_connect('key_press_event', press_event)
update(0)
Related