首页 > 解决方案 > 如何使用来自数据库而不是 .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()

任何帮助将不胜感激。提前致谢!

标签: python-3.xsqlitematplotlibanimation

解决方案


这段代码为我完成了这项工作。谢谢

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()

推荐阅读