首页 > 解决方案 > 实时变量到实时动画图 - Python

问题描述

我是 python 新手,目前正在使用变量、API 和可视化。

目前,我正在以房间温度的形式从 API 中提取一些传感器数据。

我希望能够可视化正在提取的数据,以及收集样本的实时时间。

我已经能够进入我提取实时数据的阶段以及收集数据的时间。然后将该信息存储在一个开放变量中——一个用于时间,一个用于温度读数。

我现在希望能够以图表的形式显示变量数据,当收集到新读数时,它会自行更新。

我已经能够在图表中创建并显示一个奇异读数,但这只是一个奇异图,而不是已收集的所有样本。

有什么办法可以做到这一点?

我的代码如下 - 但我已删除连接到 API 所需的信息。一切正常,直到到达“#Plotting the live data”部分。

import matplotlib
import matplotlib.pyplot as plt
import requests
import json
import sched, time
from datetime import datetime
from datetime import date
import csv
from pathlib import Path
import matplotlib
import matplotlib.pyplot as plt
import random
from itertools import count
import pandas as pd
from matplotlib.animation import FuncAnimation
import requests
import json
import sched, time
from datetime import datetime
from datetime import date
from numpy import array
import os
import re
import string
import numpy 

#-----------------------------------------------------------------------------------------------------

import urllib3
urllib3.disable_warnings()
import warnings
warnings.filterwarnings("ignore", message="Glyph 13 missing from current font.")

#-----------------------------------------------------------------------------------------------------

#open variables 
data =[]
pulltime = []

print("Pulling live data...")
#-----------------------------------------------------------------------------------------------------

#Schedule repeat after 5 seconds 
s = sched.scheduler(time.time, time.sleep)

#Pull data 
def data_pull(sc):
    print('Live reading:') 
    #Date and time pulled in 
    now = datetime.now()
    today = date.today()
    dt_string = now.strftime("%H:%M:%S")

#-----------------------------------------------------------------------------------------------------

    #Data request
    url = ""
    payload={}
    headers = {
      "Authorization": ""
    }
    response = requests.request("GET", url, headers=headers, data=payload, verify=False)

#-----------------------------------------------------------------------------------------------------

    #Variable appending 
    #Temperature 
    data.append(response.json())
    #Time of sample 
    pulltime.append(dt_string)

    #Updated Variable 
    print(pulltime + data)

#------------------------------------------------------------------------------------------------------
    #Saving data to file 
    if not Path("x.csv").is_file():
        with open("x.csv", "a", newline = '') as f:
            field_names = ['Time', 'R1Temp']


            the_writer = csv.DictWriter(f, fieldnames = field_names)

            the_writer.writeheader()
            
             
    with open("x.csv", "a", newline = '') as f:

        field_names = ['Time', 'R1Temp']  

        the_writer = csv.DictWriter(f, fieldnames = field_names)
        the_writer.writerow({'Time': dt_string, 'R1Temp': response.text})
        print('') 
        print("Office A: " + dt_string + ' - ' + response.text)
        #print("Office A: ", data , ' - ' , pulltime)

#-----------------------------------------------------------------------------------------------------

    #plotting the live data
    x = []
    y = []

    d2 = today.strftime("%d/%m/%Y")

    # Appending of the axis's
    x.append(pulltime)    
    y.append(data)

    # Plotting the line points
    plt.plot(x, y, color ="Blue", marker = "o", label = ("R1"))

   
    # Naming x axis
    plt.xlabel("Live Time")
    plt.ylabel("Temperature °C")
    # Title for the graph
    plt.title("Live temperature of Rooms in MH")
    # Show legend on the plot
    plt.legend(loc="upper left")


    
    # Function to show the plot
    plt.tight_layout()
    plt.show()
    


#-----------------------------------------------------------------------------------------------------

    #repeat after 5 seconds 
    s.enter(5,1, data_pull, (sc,))

s.enter(5, 1, data_pull, (s,))
s.run()

当包含“#Plotting live data”部分并运行代码时,这就是结果;

Pulling live data...
Live reading:
['13:56:35', '13:56:40', 21.0, 20.9]

Office A: 13:56:35 - 20.9


Traceback (most recent call last):
  File "C:\Users\gp\Desktop\saving as a variable.py", line 134, in <module>
    s.run()
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\sched.py", line 151, in run
    action(*argument, **kwargs)
  File "C:\Users\gp\Desktop\saving as a variable.py", line 109, in data_pull
    plt.plot(x, y, color ="Blue", marker = "o", label = ("R1"))
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\pyplot.py", line 2840, in plot
    return gca().plot(
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_axes.py", line 1743, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 273, in __call__
    yield from self._plot_args(this, kwargs)
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 394, in _plot_args
    self.axes.xaxis.update_units(x)
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axis.py", line 1466, in update_units
    default = self.converter.default_units(data, self)
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\category.py", line 107, in default_units
    axis.set_units(UnitData(data))
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\category.py", line 176, in __init__
    self.update(data)
  File "C:\Users\gp\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\category.py", line 209, in update
    for val in OrderedDict.fromkeys(data):
TypeError: unhashable type: 'numpy.ndarray'

标签: pythonmatplotlibvariablestimematplotlib-animation

解决方案


推荐阅读