【问题标题】:How to dynamic plot with data from database instead of .txt?如何使用来自数据库而不是 .txt 的数据进行动态绘图?
【发布时间】:2019-06-07 18:51:03
【问题描述】:

我有一个模拟传感器的代码,将随机值和时间戳放在 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.x sqlite matplotlib animation


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-19
      • 2020-06-21
      • 2020-01-19
      • 2017-12-10
      • 1970-01-01
      相关资源
      最近更新 更多