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)
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.
you can use
subplot.cla() # which clears data but not axes
subplot.clf() # which clears data and axes