Khris
Khris

Reputation: 3212

Python Matplotlib: Clear figure when figure window is not open

I'm working with matplotlib plotting and use ioff() 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 show() command.

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

Example:

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()

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

Writing P.fig.clear() 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.

Doing P.fig.clear() 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.fig.clf()
P.axes[0].clear()
P.axes[0].cla()
mpp.clf()
mpp.cla()
mpp.close(P.fig)

Wrapping the command into a class method doesn't work either:

def clearFig(self):
    self.fig.clear()

EDIT ================

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

/EDIT ================

Is it because I switched off interactive mode?

Upvotes: 1

Views: 2019

Answers (1)

Ed Smith
Ed Smith

Reputation: 13216

If you add a call to plt.draw() after P.fig.clear() it clears the figure. From the docs,

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.

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.

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

Upvotes: 1

Related Questions