So I got a small problem, but yeah, I need an answer. A created a plot with matplotlib, and after the showing I want to close it. Of course, I visited some documentation (e.g.: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.close.html), a lot of forums, like that: matplotlib close does not close the window, but my code isn't working for me.
I used the plt.ion()
function, but when I tryed it, the plot wasn't appearing, I just saw an empty window.
After that, I used the plt.show(block = False)
and I again got an empty window.
You can see the code above:
#Showing
plt.ion()
plt.show(block = False)
time.sleep(10)
plt.close("all")
As you can see, there's a delay, I would like to see a plot for ten seconds, and after close it.
Feel free, to comment to me, I appreciate that, thank you.
Do not use time.sleep()
. Use the plt.pause()
function.
Details/Explanation: First, you need plt.show(block=False)
so that the plot is not blocked and the code executes the next command.
Second, the second command i.e. plt.pause(3)
pauses the plot for 3 seconds and then goes to the next line/command.
Finally, the last line/command, plt.close("all")
closes the plot automatically.
This is a script (.py
) that plots an imshow
and automatically close it after 3 seconds.
import matplotlib.pyplot as plt
import numpy as np
X = np.random.rand(10,10)
plt.imshow(X)
plt.show(block=False)
plt.pause(3) # 3 seconds, I use 1 usually
plt.close("all")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With