我正在尝试在 python 中使用通过 API 从传感器收集并保存在变量中的数据创建一个动画图 >,这将每 5 秒更新一次并相应地绘制。
在我尝试创建图形之前,整个代码都按其应有的方式工作。
运行包含“创建图形”部分的代码时,当程序到达该部分时出现错误,但第一部分运行正常。下面是我运行代码时的结果。
Pulling live data...
Live reading:
['10:39:56', 20.8]
Office A: 10:39:56 - 20.8
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'
基于此错误,我认为该错误与保存为变量的时间有关 - 并且无法在图表上显示?但我不确定 - 任何帮助将不胜感激。
下面是我正在使用的代码,它不会运行,因为我已经删除了与 API 的连接。
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()