Is there a way to close a plot created with matplotlib from terminal (without having to close the window with mouse)

Viewed 532

Is there a way to close a plot created with matplotlib from a command in terminal (without having to close the window with mouse)?

I'm using zsh on macos 10.15.7

Let's say I have a file plot1.py with following content:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show()

from the command line, when I execute python plot1.py this opens a window displaying the plot. What I would like to do is close this window from the terminal with a keyboard command. I tried ctrl + c and ctrl + y without success and I have to close the window with the mouse by clicking on the close button

Note: I am not using anaconda (as mentioned in this question

1 Answers

You can use the block argument of the plt.show method:

import matplotlib.pyplot as plt

plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
plt.show(block=False)
plt.pause(1)
input()
plt.close()

With the above code, you can close the window whenever you press Enter in the terminal.


You also can use Alt + F4, making sure that the matplotlib window is above the terminal window. Of course, that is a windows hot key rather than a terminal shortcut...

Related