我有一个模仿传感器的代码,将随机值和时间戳记到txt文件中。通过不断更新的该文件,我可以动态绘制这些值。现在我的想法是做同样的事情,但是要从数据库中获取数据。我已经能够将服务器收到的所有数据保存到数据库中。现在是动态绘图区域。
我用于将数据保存到表中的代码:
while True:
data = conn.recv(2048).decode('utf-8')
if not data:
break
#print('Servidor recebeu :', repr(data))
t = dt.datetime.now().strftime('%H:%M:%S')
c.execute('INSERT INTO edgedata VALUES (?,?)', (data, t))
con.commit()
我从.txt文件进行动态绘图的代码:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
print("inside animate")
pullData = open("datatest.txt","r").read()
dataArray = pullData.split('\n')
xar = []
yar = []
for eachLine in dataArray:
if len(eachLine)>1:
x,y = eachLine.split(',')
xar.append(str(x))
yar.append(float(y))
ax1.clear()
ax1.plot(xar,yar)
plt.xlabel('Hora')
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.ylabel('Valor Dado')
plt.title('Pseudo-Sensor x Hora')
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
任何帮助将不胜感激。预先感谢!
答案 0 :(得分:0)
这段代码为我完成了工作。谢谢
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
print("inside animate")
con = sqlite3.connect('edgedb')
c = con.cursor()
c.execute('SELECT data, timestamp FROM edgedata')
data = c.fetchall()
datas = []
dates = []
for row in data:
datas.append(row[1])
dates.append(float(row[0]))
ax1.clear()
ax1.plot_date(datas,dates,'-')
plt.xlabel('Hora')
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.ylabel('Valor Dado')
plt.title('Pseudo-Sensor x Hora')
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()