I am plotting data on a tkinter app, using matplotlib.
As long as I start the plot with a dataset, it is just fine, but when I try to change the dataset, instead of getting a new plot in place of the old one, a new plot get add on the application, so they end up stacked.
How do I update the matplotlib figure, with new dataset? I use a button to trigger the plot, passing the data to the function. This is the relevant part of the app:
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
matplotlib.rcParams["figure.figsize"] = [2,6]
self.data_set = [1,2,3,4,5,6]
self.initUI()
def initUI(self):
self.pack(fill=BOTH, expand=1)
self.style = Style()
self.style.theme_use("default")
plotbutton = Button(self, text="Plot Data", command=lambda: self.create_plot(self.data_set))
calculatebutton.place(x=300, y=600)
quitbutton = Button(self, text="Quit", command=self.quit)
quitbutton.place(x=400, y=600)
def create_plot(self, dataset):
plt = Figure(figsize=(4, 4), dpi=100)
a = plt.add_subplot(211)
a.plot(dataset, '-o', label="Main response(ms)")
a.set_ylabel("milliseconds")
a.set_title("plot")
canvas = FigureCanvasTkAgg(plt, self)
canvas.show()
canvas.get_tk_widget().pack(fill=BOTH)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(fill=BOTH)
# generate a random list of 6 numbers for sake of simplicity, for the next plot
data_set = random.sample(range(30), 6)
return
def main():
root = Tk()
root.wm_title("generic app")
root.geometry("800x700+100+100")
app = Application(master=root)
app.mainloop()
return 0
clear()which remove old plotFigure,plotandcanvas- soclear()make no sence - and you usepack()to add it but you don't remove old one.pack()is used to add new element below other elements - it doesn't replace elements. You have to usepack_forget()to remove oldcanvas. (Or maybe better usedestroy())