Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to leave matplotlib figure opened after script ends?

Suppose I have the following script plotting a graph for me:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

img = mpimg.imread('stinkbug.png')
#circle = plt.Circle((0, 0), radius=0.5, fc='y')
circle = plt.Circle((0, 0), radius=100, fill=False, color='b')

fig, ax = plt.subplots()
ax.imshow(img)
ax.add_artist(circle)
fig.show()
pass

Unfortunately, the figure closes after the script ends.

How to prevent that?

UPDATE

If it is impossible for the figure to survive the script, then what is the reason for it? What is the connection between the figure and the script?

like image 247
Suzan Cioc Avatar asked Aug 03 '26 09:08

Suzan Cioc


1 Answers

You can't. The figure created by your script can't survive after the script has ended. But maybe you do not need that, you can make your script wait for you to close the figure window instead. Just be sure interactive mode is not activated.

import matplotlib.pyplot as plt
plt.ioff()  # Use non-interactive mode.
plt.plot([0, 1])  # You won't see the figure yet.
plt.show()  # Show the figure. Won't return until the figure is closed.
like image 98
Stop harming Monica Avatar answered Aug 05 '26 23:08

Stop harming Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!