brownser
brownser

Reputation: 632

Close a matplotlib figure using keyboard

I'm plotting 2 graphs in the same figure inside a 'for' loop. The problem is that, in order to keep the loop running I have to manually close the figure using the mouse. This is difficult as the loop is over 300 steps long. I'm looking for a simpler solution, like clicking the number 1 to close the current figure and view next. I tried with the following code, and it is not working. I believe that the succeeding line is only read after the existing graph is closed. How to fix this?

P.S : Also, using raw_input() for the keypress is not a good way, as I have to additionally hit the 'Enter'. So suggest an alternate method where I can close the graphs by continuously pressing '1' .

for roww in range (0,height) :
        com = 0
        isignal = matrix[roww]
        fft_ith = np.fft.fft(isignal)
        fft_abs_ith = np.abs(fft_ith)
        c_fft = fft_abs_ith[:len(fft_abs_ith)//2] 
        c_fft[zi] = 0


        plt.subplot(2,1,1)
        plt.plot(time,isignal,marker='.')
        plt.xlim(0,time[len(time)-1])
        plt.title("Individual oscilations  and FFT of each cell \n cell ="+str(roww))
        plt.subplot(2,1,2)
        plt.plot(c_freqq,c_fft,marker = ".")
        plt.show()
comnd = raw_input()
if comnd == 1
        plt.close()


Upvotes: 0

Views: 2664

Answers (3)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339795

By default matplotlib figures can be closed using the q key. If instead you want to use the 1 key you can add

plt.rcParams["keymap.quit"] = "1"

somewhere on top of your script.

You can set it to plt.rcParams["keymap.quit"] = ['ctrl+w', 'cmd+w', 'q'] or whatever you like.

Upvotes: 3

gustavovelascoh
gustavovelascoh

Reputation: 1228

This is not a direct response to your question but could be useful with some modifications. In the code referred, I create a figure and, instead of replotting or closing the window, I update the lines objects created.

gif

Code is at: https://github.com/gustavovelascoh/plot_update

Upvotes: 0

Kamil Machon
Kamil Machon

Reputation: 26

The raw_input() function returns a string, so you need to cast comnd to an integer or replace the "1" in your if statement with '1'.

Upvotes: 0

Related Questions