[英]Update a matlib plot in tkinter canvas
我正在制作一個應用程序,用戶輸入數據並將結果顯示在圖表上。 我希望每次輸入新數據時都會更新繪圖,但不會更新繪圖。
繪圖是使用 matlib 繪圖庫生成的,界面是使用 tkinter 包創建的。 它的完成方式是使用一個函數來創建繪圖,因為我想多次調用它。 我認為問題可能是函數返回變量的方式,但我無法確定這是錯誤的原因或原因。
我在這里尋找解決方案,但我讀過的所有解決方案似乎都不起作用。 我試圖更新我的軸,使用patlibplot.figure
而不是matlibplot.plot
,將canvas.daw()
添加到最后,甚至試圖獲得一種生成繪圖的新方法。
這是創建繪圖的函數:
import matplotlib.pyplot as plt
def PlotConsumption(fuelEntry, plotConfig):
'''
Produce a line plot of the consumption
:params object fuelEntry: all of the fuel entry information
:params object plotConfig: the config object for the plot
'''
# create a data frame for plotting
df = pd.DataFrame(fuelEntry)
df = df.sort_values(["sort"]) # ensure the order is correct
df["dateTime"] = pd.to_datetime(df["date"], format="%d/%m/%Y") # create a date-time version of the date string
if plotConfig.xName == "date": # change the indexing for dates
ax = df.plot(x = "dateTime", y = plotConfig.yName, marker = '.', rot = 90, title = plotConfig.title)
else:
ax = df.plot(x = plotConfig.xName, y = plotConfig.yName, marker = '.', title = plotConfig.title)
# calculate the moving average if applicable
if plotConfig.moveCalc == True and plotConfig.move > 1 and len(df) > plotConfig.move:
newName = plotConfig.yName + "_ma"
df[newName] = df[plotConfig.yName].rolling(window = plotConfig.move).mean()
if plotConfig.xName == "date":
df.plot(x = "dateTime", y = newName, marker = "*", ax = ax)
else:
df.plot(x = plotConfig.xName, y = newName, marker = "*", ax = ax)
# tidy up the plot
ax.set(xlabel = plotConfig.xLabel, ylabel = plotConfig.yLabel)
plt.setp(ax.xaxis.get_majorticklabels(), rotation=90)
L=plt.legend()
L.get_texts()[0].set_text(plotConfig.yLegend)
if len(L.get_texts()) == 2: # only process if there is a moving average plot
L.get_texts()[1].set_text(plotConfig.moveLegend)
return plt # also tried with returning ax
這是使用它的地方:
self.plot = displayCharts.PlotConsumption(self.data.carEntry["fuelEntry"], self.plotConfig)
#fig = plt.figure(1) # also tried creating fig this way
fig = self.plot.figure(1)
self.plotCanvas = FigureCanvasTkAgg(fig, master = self.master)
self.plotWidget = self.plotCanvas.get_tk_widget()
self.plotWidget.grid(row = 0, column = 1, rowspan = 3, sticky = tk.N)
fig.canvas.draw()
我希望情節自動更新,但它什么也不做。 我知道讀取和處理數據就像關閉應用程序一樣,再次啟動它,然后加載生成的圖正確的相同數據文件。
我重新審視了我最初看到的一些答案並選擇了它們, 這是我找到的最好的答案,它實際上滿足了我的要求!
我需要更改一些細微的差異:
我復制了鏈接的解決方案以查看它是如何工作的並設法讓它工作。 現在下一步是讓它與我的數據一起繪制! 但是現在我已經更新了它應該更容易完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.