python-3.x - 如何使用来自数据库而不是 .txt 的数据进行动态绘图?
问题描述
我有一个模仿传感器的代码,将随机值和时间戳放在 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()
任何帮助将不胜感激。提前致谢!
解决方案
这段代码为我完成了这项工作。谢谢
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()
推荐阅读
- excel - VBS通过部分名称打开文件在网络驱动器上运行但不是本地
- android - 获取未处理的异常:FormatException:flutter API 响应中的输入意外结束(在字符 1 处)
- azure - Azure NotificationHubClient 在 Azure 函数上密集使用时抛出 SocketException
- r - 如何使用列索引从 R 中的列中收集值
- javascript - Apollo GraphQL 变量参数名称
- blazor - 如何修复 app.razor 中的 Blazor webassembly 3.2.0 预览 2 更新问题?
- reactjs - 在功能组件中使用道具
- angular - 具有子入口点循环依赖的Angular 9库
- laravel - Laravel 迁移一般错误:1215 无法添加外键约束 Laravel 7.x
- parallel-processing - 我可以将 OpenACC 用于多核 CPU 吗?