Barzi2001
Barzi2001

Reputation: 1766

Event handling and picking does not work with Spyder

When I run the following script in a IPython (IPython 8.2.0) console opened from Anaconda powershell I am allowed to pick points from the figure. Then, the script continues only once I close the figure, as it should be.

However, when I run the same script on Spyder this won't happen: the script won't allow me to pick any point from the figure but it continues straight to the end, thus always resulting in printing tin = 0 and tout = 0 and returning the IPython prompt.

import numpy as np
import matplotlib.pyplot as plt

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

ax[0, 0].plot(np.random.rand(10))
ax[0, 1].plot(np.random.rand(10))
ax[1, 0].plot(np.random.rand(10))
ax[1, 1].plot(np.random.rand(10))


def onclick(event):
    if onclick.index == 0:
        onclick.tin = np.round(event.xdata, 3)
    else:
        onclick.tout = np.round(event.xdata, 3)
    print('tin = ', onclick.tin, 'tout =', onclick.tout, end='\r')
    onclick.index = (onclick.index+1) % 2


onclick.index = 0
onclick.tin = 0
onclick.tout = 0

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
fig.canvas.mpl_disconnect(cid)
tin = onclick.tin
tout = onclick.tout
print('\n\n tin = ', tin, 'tout =', tout, end='\r')

I am running the following version of Spyder:

Upvotes: 1

Views: 359

Answers (1)

Carlos Cordoba
Carlos Cordoba

Reputation: 34156

There are two ways to achieve this:

  1. You can change your plt.show() call to

    plt.show(block=True)
    

    However, after closing the figure, you need to press Ctrl + C in the console to get the prompt back on it.

  2. You can add the code in this answer just below plt.show(). The advantage of that is that you'll get the prompt back after closing the figure.

Upvotes: 2

Related Questions