我在这里重新绘制图形时遇到了问题。我允许用户指定时间尺度(x 轴)中的单位,然后我重新计算并调用此函数plots()。我希望绘图只是更新,而不是将另一个绘图附加到图形中。
plots()
def plots(): global vlgaBuffSorted cntr() result = collections.defaultdict(list) for d in vlgaBuffSorted: result[d['event']].append(d) result_list = result.values() f = Figure() graph1 = f.add_subplot(211) graph2 = f.add_subplot(212,sharex=graph1) for item in result_list: tL = [] vgsL = [] vdsL = [] isubL = [] for dict in item: tL.append(dict['time']) vgsL.append(dict['vgs']) vdsL.append(dict['vds']) isubL.append(dict['isub']) graph1.plot(tL,vdsL,'bo',label='a') graph1.plot(tL,vgsL,'rp',label='b') graph2.plot(tL,isubL,'b-',label='c') plotCanvas = FigureCanvasTkAgg(f, pltFrame) toolbar = NavigationToolbar2TkAgg(plotCanvas, pltFrame) toolbar.pack(side=BOTTOM) plotCanvas.get_tk_widget().pack(side=TOP)
要更新绘图而不是将新绘图附加到图形,您应该清除现有图形,然后重新绘制数据。此外,确保每次调用函数时都不会重新创建FigureCanvasTkAgg和实例。相反,您可以创建它们一次,然后只需重新绘制画布即可重复使用它们。NavigationToolbar2TkAgg``plots
FigureCanvasTkAgg
NavigationToolbar2TkAgg``plots
您可以按照以下方法修改代码来实现此目的:
plots
这是您的代码的修订版本:
Python复制代码import collections from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from tkinter import TOP, BOTTOM # Initialize the figure, canvas, and toolbar outside the function f = Figure() graph1 = f.add_subplot(211) graph2 = f.add_subplot(212, sharex=graph1) plotCanvas = FigureCanvasTkAgg(f, pltFrame) toolbar = NavigationToolbar2TkAgg(plotCanvas, pltFrame) toolbar.pack(side=BOTTOM) plotCanvas.get_tk_widget().pack(side=TOP) def plots(): global vlgaBuffSorted cntr() result = collections.defaultdict(list) for d in vlgaBuffSorted: result[d['event']].append(d) result_list = result.values() # Clear existing plots graph1.clear() graph2.clear() for item in result_list: tL = [] vgsL = [] vdsL = [] isubL = [] for dict in item: tL.append(dict['time']) vgsL.append(dict['vgs']) vdsL.append(dict['vds']) isubL.append(dict['isub']) graph1.plot(tL, vdsL, 'bo', label='a') graph1.plot(tL, vgsL, 'rp', label='b') graph2.plot(tL, isubL, 'b-', label='c') # Redraw the canvas plotCanvas.draw() # Example usage: call plots() whenever you need to update the plot # plots()
graph1.clear()
graph2.clear()
plotCanvas.draw()
通过遵循这些步骤,您可以确保正确更新图表,而不会在旧图表之上添加新图表。