I am writing a widget to allow me to browse a large data set in a human-useable manner, using drop-down boxes to select a combination of variables to produce an image from the data files (using matplotlib). However, I am running into trouble updating the image: rather than clearing the old image and putting a new one in its place, a new subplot seems to be created and attached to the old plot.
I am executing the code on a Mac box. The data file selection process works correctly, so I will omit that. For the image generating portion I have tried pulling code from several demos (including here, here, and here) with limited success - some iterations have correctly produced images, but are none have been able to correctly update the image when the file selection is changed. (As an aside, I get errors "FigureCanvasTkAgg object has no attribute X" when trying to use the commands canvas.clear() and canvas.show(), which are used in the above-mentioned demos.)
The code governing my initial image generation, where Fname is defined elsewhere:
self.fig = plt.figure(figsize=(5,5)) # Initialize a figure.
self.ax = self.fig.add_axes([1,1,1,1]) # Give it axes that I can manipulate.
self.ax.clear() # The axis should be clear already, but clear it anyway.
if os.path.exists('./Data/'+Fname) == False:
# Making sure the data file is there to avoid read errors.
print('Data hole.')
self.ax.plot([0,1],[0,1])
else: # Data file exists, we may proceed
data = np.loadtxt('./Data/'+Fname).T # From Numpy; open the data file
self.ax.plot(data[0],data[1]) # Plot the data
# Everything from here...
self.canvas = FigureCanvasTkAgg(self.fig,self)
self.canvas.get_tk_widget().pack(side=BOTTOM,fill=BOTH,expand=True)
self.canvas.draw()
toolbar = NavigationToolbar2Tk(self.canvas,root)
toolbar.update()
self.canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=True)
# ...to here was pulled from a demo and tweaked to match my varnames.
# I actually don't know what it does.
When a selection is made from a dropdown menu, Fname is changed and a change_dropdown() function is called:
if os.path.exists('./Data/'+Fname) == False:
# Make sure the data exists. Do not update the plot if there is no data.
print('Data hole.')
else:
data = np.loadtxt('./Data/'+Fname).T
self.ax.clear()
self.ax.plot(data[0],data[1]) # Very similar to my original plotting.
canvas = FigureCanvasTkAgg(self.fig,self)
canvas.get_tk_widget().pack(side=BOTTOM,fill=BOTH,expand=True)
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas,root)
toolbar.update()
canvas.get_tk_widget().pack(side=TOP,fill=BOTH,expand=True)
I expected that each time the dropdown is changed, the existing figure would be cleared and a new image plotted. Instead, I get a new plot attached to the old plot, seemingly as another subplot. This often pushes the dropdown menus out of the visible frame.