0

I am new to python and am currently working with Variables, APis and visualisation.

Currently I am pulling some sensor data from a API in the form of a temperature for a room.

I want to be able to visualise the data that is being pulled, as well as the live time that the samples have been collected at.

I have been able to get to the stage where I have pulled in the live data and the time that the data was collected. This information is then stored in an open variable - one for the time and one for the temperature readings.

I now want to be able to display the variables data in the form of a graph, that will update itself when a new reading has been collected.

I have been able to create and display a singular reading in the graph, but it is only a singular plot, not all the samples that have been collected.

Is there any way in which this could be done?

My code is below - But I have removed the information that is required to connect to the API. Everything works how it should, until the '#Plotting the live data' part is reached.

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

When the '#Plotting live data' part is included and the code is run, this is the out come;

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'
HWJ5
  • 17
  • 5
  • 1
    I'd recommend Dash, pretty simple live graphing. https://dash.plotly.com/ Sentdex has nice youtube series about that https://www.youtube.com/watch?v=J_Cy_QjG6NE&list=PLQVvvaa0QuDfsGImWNt1eUEveHOepkjqt&ab_channel=sentdex – Leemosh Jan 04 '21 at 15:51
  • @Leemosh Thank you - I shall check that out! – HWJ5 Jan 04 '21 at 15:53

0 Answers0