Closing pyplot windows
plt.close()
will close current instance.
plt.close(2)
will close figure 2
plt.close(plot1)
will close figure with instance plot1
plt.close('all')
will close all fiures
Found here.
Remember that plt.show()
is a blocking function, so in the example code you used above, plt.close()
isn't being executed until the window is closed, which makes it redundant.
You can use plt.ion()
at the beginning of your code to make it non-blocking, although this has other implications.
EXAMPLE
After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.
Below I create a plot:
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')
In this case, ax
above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax)
.
par_plot
is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.
I can also create a slider widget by doing the following:
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
The first line creates a new axes for the slider (called axsliderA
), the second line creates a slider instance sA
which is placed in the axes, and the third line specifies a function to call when the slider value changes (update
).
My update function could look something like this:
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
The par_plot.set_ydata(y_data)
changes the ydata property of the Line2D object with the handle par_plot
.
The draw()
function updates the current set of axes.
Putting it all together:
from pylab import *
import matplotlib.pyplot as plt
import numpy
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
x_data = numpy.arange(-100,100,0.1);
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)
ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)
axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)
axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;
par_plot, = plot(x_data,y_data, lw=2, color='red')
show()
A note about the above: When I run the application, the code runs sequentially right through (it stores the update
function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).
This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.
Matplotlib -Close window without explicit mouseclick
Here is another solution, using an explicit close
statement to close then recreate the figure at each iteration
from matplotlib import gridspec
import matplotlib.pyplot as plt
import numpy as np
def plot_stuff(x, y, z):
gs = gridspec.GridSpec(3, 1)
plt.style.use('dark_background')
fig = plt.figure("1D Analysis")
ax = plt.subplot(gs[0, 0])
ax.set_ylabel('X VALUE')
plt.plot(x, color="red")
ax = plt.subplot(gs[1, 0])
ax.set_ylabel('Y VALUE')
plt.plot(y, color="green")
ax = plt.subplot(gs[2, :])
ax.set_ylabel('Z VALUE')
plt.plot(z, color="blue")
return fig
things_to_plot = [np.random.random(size=(100, 3)),
np.ones((100, 3)),
np.random.random(size=(100, 3))]
delay = 5
if __name__ == "__main__":
plt.ion()
for things in things_to_plot:
fig = plot_stuff(x=things[:, 0], y=things[:, 1], z=things[:, 2])
plt.show()
plt.pause(delay)
plt.close()
view and then close the figure automatically in matplotlib?
Documentation on pyplot.show()
reads:
matplotlib.pyplot.show(*args, **kw)
Display a figure. When running in ipython with its pylab mode, display
all figures and return to the ipython prompt.In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect
unless figures were created prior to a change from non-interactive to
interactive mode (not recommended). In that case it displays the
figures but does not block.A single experimental keyword argument,
block
, may be set toTrue
orFalse
to override the blocking behavior described above.
So the solution is this:
plt.show(block=False)
plt.pause(3)
plt.close()
Is there a way to close a plot created with matplotlib from terminal (without having to close the window with mouse)
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...
How to programatically close a matplotlib window?
Thank you for the comments. It looks like it might be a bug in the Tkinter backend. Switching to the Qt4Agg backend results in the expected behavior where plt.close() closes the window as expected.
Closing a matplotlib figure in Pycharm
I guess you use the SciView. So you need to change the setting in the pycharm.
Settings | Tools | Python Scientific | Show Plots in Toolwindow - box has to be unticked to back to the usual matplotlib figure window
After this, try again.
matplotlib close does not close the window
you have to specify wich figure you want to close. In case you want to close all of them:
pl.close('all')
Also, there is a way to just clear but not close a figure:
pl.clf()
Also, seen below from another SO question:
Remember that
plt.show()
is a blocking function, so in the example code you used above,plt.close()
isn't being executed until the window is closed, which makes it redundant.You can use
plt.ion()
at the beginning of your code to make it non-blocking, although this has other implications.
Related Topics
Replace Invalid Values with None in Pandas Dataframe
How to Use a String as a Keyword Argument
Monkey Patching a Class in Another Module in Python
What Is the Best Approach to Change Primary Keys in an Existing Django App
Python Pandas - Missing Required Dependencies ['Numpy'] 1
Checking Odd/Even Numbers and Changing Outputs on Number Size
How to Change Foreignkey Display Text in the Django Admin
Securely Erasing Password in Memory (Python)
Python List Comprehension - Want to Avoid Repeated Evaluation
How to Create an Object and Add Attributes to It
Filedialog, Tkinter and Opening Files
Unicodeencodeerror: 'Ascii' Codec Can't Encode Character at Special Name
Passing a Function to Re.Sub in Python
Generating Discrete Random Variables with Specified Weights Using Scipy or Numpy