我在这里重新绘制图形时遇到问题。我允许用户在时间刻度(x轴)中指定单位,然后重新计算并调用此函数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)
你基本上有两个选择:
精确执行当前操作,但在重新配置数据之前先致电graph1.clear()和graph2.clear()。这是最慢但最简单,最可靠的选择。
graph1.clear()
graph2.clear()
除了重新绘制外,你还可以更新绘图对象的数据。你需要在代码中进行一些更改,但这比每次重新绘制都快得多。但是,你要绘制的数据的形状无法更改,并且如果数据范围正在更改,则需要手动重置x和y轴限制。
举一个第二种选择的例子:
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 6*np.pi, 100) y = np.sin(x) # You probably won't need this if you're embedding things in a tkinter plot... plt.ion() fig = plt.figure() ax = fig.add_subplot(111) line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma for phase in np.linspace(0, 10*np.pi, 500): line1.set_ydata(np.sin(x + phase)) fig.canvas.draw() fig.canvas.flush_events()