【发布时间】:2019-12-30 12:19:41
【问题描述】:
我正在制作一个用户输入数据并将结果显示在图表上的应用程序。我希望每次输入新数据时都更新绘图,但不会更新绘图。
绘图是使用 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()
我希望情节会自动更新,但它什么也没做。我知道数据的读取和处理就像您关闭应用程序一样,再次启动它,然后加载相同的数据文件,生成的绘图是正确的。
【问题讨论】:
标签: python matplotlib tkinter