我想在基于时间的图表中绘制传感器日期,该图表应嵌入Tkinter窗口中。目前,我只想绘制y1List与xList。
到目前为止,我还没有找到针对特定用例的stackoverflow解决方案。
我的代码:
import datetime # für Datum/Uhrzeit
from tkinter import * # für GUI
import numpy as np
import matplotlib as mpl
import matplotlib.backends.tkagg as tkagg
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
#Animation function
def animate(ax,xList,y1List,y2List):
time = datetime.datetime.now().strftime("%H:%M:%S")
lb_Time.config(text=time)
lb_Time['text'] = time
xList.append(time)
# Replace sample data below my real data...
y1List.append(np.sin(len(xList)))
y2List.append(2*np.sin(len(xList)))
# Limit x and y lists to 20 items
xList = xList[-20:]
y1List = y1List[-20:]
y2List = y2List[-20:]
line, = ax.plot_date(mpl.dates.datestr2num(xList), y1List)
plt.show()
fenster.after(1000,animate,ax,xList,y1List,y2List)
fenster = Tk()
fenster.title("Monitoring")
fenster.geometry("450x400")
lb_Time = Label(fenster)
exit_button = Button(fenster, text="Beenden", command=fenster.destroy, fg="red")
lb_Time.grid(row=2, column=0,pady=20)
xList = []
y1List =[]
y2List = []
fig = plt.Figure(figsize=(2, 2))
canvas = FigureCanvasTkAgg(fig, master=fenster)
canvas.get_tk_widget().grid(row=3,column=1,pady=20)
ax = fig.add_subplot(111)
line, = ax.plot_date(xList, y1List)
animate(ax,xList,y1List,y2List)
fenster.mainloop()
我的问题是,该图仅是静态的,并且在y值为34时仅绘制了1个点。为什么不每1秒更新一次,为什么根本不更新34(因为我使用过窦...)? >
答案 0 :(得分:0)
我已经使用这段代码完成了
...
from matplotlib.animation import FuncAnimation
...
_ANIM_INTERVAL = 1000 # Milliseconds.
def animate(counter: int) -> None:
"""Refresh graph.
:param counter: Function call counter (2 times for 0!!!).
"""
...
...
_ = FuncAnimation(fig, animate, interval=_ANIM_INTERVAL)
show(fig)
JM
答案 1 :(得分:0)
mainloop是一个阻塞语句,即当遇到它时,现在将运行更多代码。您可以通过在主循环后放置一个打印语句来验证这一点。我对tkinter的内部工作不太熟悉,但是可以使用本地matplotlib轻松地编写动画功能:
import numpy as np, matplotlib.pyplot as plt
fig, ax = plt.subplots()
# dummy data
N = 100
buffer = np.zeros((N, 2))
p = ax.plot(*buffer.T, marker = '.')[0] # get plot object
while True:
for idx in range(N):
buffer[idx, :] = np.random.rand(buffer.shape[1])
p.set_data(*buffer.T)
# recompute data limits
ax.relim()
ax.axes.autoscale_view(True, True, True)
# update figure; flush events
fig.canvas.draw()
fig.canvas.flush_events()