Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear figure subplots matplotlib python

I wrote a simple Python function to generate a matplotlib figure. I call plotData multiple times from a separate script, but each time it generates a new plot. What I would like is to always have just one plot with something like subplot.clear() to clear the subplots between data changes.

I need a way to identify the figure from outside plotData so that I can clear the plots for new data. What would be the best way to accomplish this?

## Plot Data Function
def plotData(self):

        # Setup figure to hold subplots
        f = Figure(figsize=(10,8), dpi=100)

        # Setup subplots
        subplot1=f.add_subplot(2,1,1)
        subplot2=f.add_subplot(2,1,2)

        # Show plots
        dataPlot = FigureCanvasTkAgg(f, master=app)
        dataPlot.show()
        dataPlot.get_tk_widget().pack(side=RIGHT, fill=BOTH, expand=1)
like image 538
Spencer H Avatar asked Feb 02 '17 20:02

Spencer H


People also ask

How do I clear the subplot in matplotlib?

The Matplotlib cla() function can be used as axes. clear() function. Similarly, the clf() function makes figure clear. Both cla() and clf() clears plot in Matplotlib.

What does PLT close () do?

plt. close() closes a window, which will be the current window, if not specified otherwise.


1 Answers

I'm not sure if I fully understand where the problem lies. If you want to update the plot you would need a function that does this. I would call this function plotData. Before that you also need to set the plot up. That is what you currently have in plotData. So let's rename that to generatePlot.

class SomeClass():
    ...

    def generatePlot(self):
        # Setup figure to hold subplots
        f = Figure(figsize=(10,8), dpi=100)

        # Setup subplots
        self.subplot1=f.add_subplot(2,1,1)
        self.subplot2=f.add_subplot(2,1,2)

        # Show plots
        dataPlot = FigureCanvasTkAgg(f, master=app)
        dataPlot.show()
        dataPlot.get_tk_widget().pack(side=RIGHT, fill=BOTH, expand=1)

    ## Plot Data Function
    def plotData(self, data, otherdata):
        #clear subplots
        self.subplot1.cla()
        self.subplot2.cla()
        #plot new data to the same axes
        self.subplot1.plot(data)
        self.subplot2.plot(otherdata)

Now you need to call generatePlot only once at the beginning. Afterwards you can update your plot with new data whenever you want.

like image 176
ImportanceOfBeingErnest Avatar answered Sep 20 '22 01:09

ImportanceOfBeingErnest