Python Matplotlib: Clear figure when figure window is not open
<p>I'm working with matplotlib plotting and use <code>ioff()</code> to switch interactive mode off to suppress the automatic opening of the plotting window on figrue creation. I want to have full control over the figure and only see it when explicitely using the <code>show()</code> command.</p>

<p>Now apparently the built-in commands to clear figures and axes do not work properly anymore.</p>

<p>Example:</p>

<pre><code>import numpy as np
import matplotlib.pyplot as mpp

class PlotTest:

    def __init__(self,nx=1,ny=1):
        # Switch off interactive mode:
        mpp.ioff()

        # Create Figure and Axes:
        self.createFigure(nx, ny)

    def createFigure(self,nx=1,ny=1):
        self.fig, self.axes = mpp.subplots(nx,ny)
        if nx*ny == 1:
            self.axes = np.array([self.axes])

    def linePlot(self):
        X = np.linspace(0,20,21)
        Y = np.random.rand(21)     
        self.axes[0].plot(X,Y)

P = PlotTest()
P.linePlot()
P.fig.show()
</code></pre>

<p>Now I was thinking I could use <code>P.fig.clear()</code> any time to simply clear <code>P.fig</code>, but apparently that's not the case.</p>

<p>Writing <code>P.fig.clear()</code> directly into the script and execute it together it works and all I see is an empty figure. However that's rather pointless as I never get to see the actual plot like that.</p>

<p>Doing <code>P.fig.clear()</code> manually in the console does not do anything, regardless if the plot window is open or not, all other possible commands fail as well:</p>

<pre><code>P.fig.clf()
P.axes[0].clear()
P.axes[0].cla()
mpp.clf()
mpp.cla()
mpp.close(P.fig)
</code></pre>

<p>Wrapping the command into a class method doesn't work either:</p>

<pre><code>def clearFig(self):
    self.fig.clear()
</code></pre>

<p>EDIT ================</p>

<p>After a <code>clear()</code> <code>fig.axes</code> is empty, yet <code>show()</code> still shows the old plot with the axes still being plotted.</p>

<p>/EDIT ================</p>

<p>Is it because I switched off interactive mode?</p>

<p>If you add a call to <code>plt.draw()</code> after <code>P.fig.clear()</code> it clears the figure. From the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.draw" rel="nofollow">docs</a>,</p>

<blockquote>
  <p>This is used in interactive mode to update a figure that has been altered, but not automatically re-drawn. This should be only rarely needed, but there may be ways to modify the state of a figure with out marking it as stale. Please report these cases as bugs.</p>
</blockquote>

<p>I guess this is not a bug as you have switched off interactive mode so it is now your responsibility to explicitly redraw when you want to.</p>

<p>You can also use <code>P.fig.canvas.draw_idle()</code> which could be wrapper in the class as <code>clearFigure</code> method.</p>

python matplotlib plot