Live Plot of Data in Matplotlib - Time Series Visualization with Time on the x-axis

Is it possible to use time as x-axis values for a live matplotlib graph? If so, how should it be implemented? Despite trying various methods, I keep encountering errors. Below is my current code:


update_label(label):

    def getvoltage():

        f=open("VoltageReadings.txt", "a+")
        readings = [0]*100
        maxsample = 100
        counter = 0

        while (counter < maxsample):

            reading = adc.read_adc(0, gain=GAIN)
            readings.append(reading)
            counter += 1

        avg = sum(readings)/100
        voltage = (avg * 0.1259)/100
        time = str(datetime.datetime.now().time())
        f.write("%.2f," % (voltage) + time + "\r\n")
        readings.clear()

        label.config(text=str('Voltage: {0:.2f}'.format(voltage)))
        label.after(1000, getvoltage)
    getvoltage()

def animate(i):
    pullData = open("VoltageReadings.txt","r").read()
    dataList = pullData.split('\n')
    xList=[]
    yList=[]
    for eachLine in dataList:
        if len(eachLine) > 1:
            y, x = eachLine.split(',')
            xList.append(float(x)))
            yList.append(float(y))
            a.clear()
    a.plot(xList,yList)

Even after trying the above method, I am receiving an error message that states

ValueError: could not convert string to float: '17:21:55'

I have attempted to convert the string into a float but have been unsuccessful.

Your help and guidance would be greatly appreciated, thank you :)

Answer №1

If you're looking to work with dates in Python, I recommend using the datetime library. To begin, you can utilize the datetime.strptime command to read your dates. For example, by setting a reference date using Julian date like

date=datetime.strptime('17:21:55','%H:%M:%S')
. Another approach is to set your starting point as a date0 and then define your date as
date=datetime.strptime('01-01-2000 17:21:55','%d-%m-%Y %H%H:%M:%S')
. By calculating the differences between your current date and the reference date in seconds for each line in your file using a loop, you can store these differences in a list element (referred to as Diff_list). Finally, converting the timestamp values from Diff_List to UTC format using
T_plot= [dtm.datetime.utcfromtimestamp(i) for i in Diff_List]
, you can visualize the dates on the x-axis with plt.plot(T_plot,values).

An alternative option is to make use of the pandas library. Firstly, define your date parsing based on the type of dates in your file like

parser=pd.datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
. Then proceed to read your file with the necessary configurations:

tmp = pd.read_csv(your_file, parse_dates={'datetime': ['date', 'time']},                          date_parser=parser, comment='#',delim_whitespace=True,names=['date', 'time', 'Values'])

data = tmp.set_index(tmp['datetime']).drop('datetime', axis=1)

If you only need to represent hours HH:MM:SS instead of the complete date, you can adjust these lines accordingly. Remember, indexing will not be sequential but based on the dates themselves. Therefore, when plotting, ensure to call import matplotlib.pyplot as plt and then plt.plot(data.index,data.Values) to display your data.

Answer №2

If you're looking to visualize data from various sources at the same time, consider using the polt Python package that I have personally developed for this specific purpose. The polt package leverages matplotlib to generate multi-source data displays.

To get started, create a script called adc_read.py that fetches readings from your ADC and prints them:

import random, sys, time

def read_adc():
    """
    Add your code here to read voltage values from your ADC
    """
    # Simulate measurement delay/sampling interval
    time.sleep(0.001)
    # Simulate reading a voltage between 0 and 5V
    return random.uniform(0, 5)


while True:
    # Collect 100 readings
    adc_readings = tuple(read_adc() for i in range(100))
    # Calculate average
    adc_average = sum(adc_readings) / len(adc_readings)
    # Output the average
    print(adc_average)
    sys.stdout.flush()

This script will output results like:

python3 adc_read.py
# Output
2.3187490696344444
2.40019412977279
2.3702603804716555
2.3793495215651435
2.5596985467604703
2.5433401603774413
2.6048815735614004
2.350392397280291
2.4372325168231948
2.5618046803145647
...

You can then pipe this output into polt for live data visualization:

python3 adc_read.py | polt live

https://i.stack.imgur.com/jjA9K.png

To add labels, include metadata:

python3 adc_read.py | \
    polt \
        add-source -c- -o name=ADC \
        add-filter -f metadata -o set-quantity=voltage -o set-unit='V' \
        live

https://i.stack.imgur.com/uIreo.png

The polt documentation offers insights into further customization options.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for generating grouped and stacked bar charts

Dealing with a large dataset that includes multiple subsidiaries catering to three distinct customer groups across different countries can be quite challenging. Even though the provided example is simplified, the reality involves significantly more subsidi ...

Extracting the number of likes from each post on a specific profile using Python scrapy

Here is the code snippet that I am currently working with: #IMPORT THESE PACKAGES import requests import selenium from selenium import webdriver import pandas as pd #OPTIONAL PACKAGE, BUY MAYBE NEEDED from webdriver_manager.chrome import ChromeDriverManage ...

Unlock autofill suggestions when modifying methods from parent Python class within VS code

In IntelliJ, there is a feature that provides autocomplete and assistance for adding an inherited function. Is it possible to achieve the same behavior in VS Code using the built-in Python interpreter? This feature allows us to override specific function ...

Remove an additional bracket from a given list

I am working with a list in Python that looks like this: results = [[['New','York','intrepid', 'bumbling']], [['duo', 'deliver', 'good', 'one']]] My goal is to transform it i ...

What is the best way to combine and merge multiple JSON files from a folder into one consolidated JSON file using Python?

Imagine you have 3 JSON files - data1.json, data2.json, and data3.json. Let's take a look at what each file contains: { "Players":[ { "name":"Alexis Sanchez", "club":"Manchester United" }, { "name" ...

why does the 'del' keyword not effectively remove a list when used within a function parameter?

When I use the del keyword to delete the formal parameter a, the list that is passed still exists when printed outside the function in the following code. lst = [1,2,3] def func(a): print lst lst.append(4) # This change affects it as it is passe ...

How does Word2vec perform its operations on analogies?

Based on information found at https://code.google.com/archive/p/word2vec/: A recent discovery revealed that word vectors are able to capture various linguistic regularities. For instance, performing vector operations like vector('Paris') - ve ...

Comparing frozensets in Python

Take a look at this script: # A list of 7 frozensets with different numbers of string objects multipleSmallFrozensets = [ frozenset({'YHR007C', 'YHR042W'}), frozenset({'YPL274W'}), frozenset({'YCL064C'}) ...

Determining the scope of values within a numpy array

I am working with a NumPy array that has dimensions of 94 x 155: a = [1 2 20 68 210 290.. 2 33 34 55 230 340.. .. .. ... ... .... .....] My goal is to find the range for each row, resulting in 94 different ranges. I have searched for a ...

Within the flask framework, I am experiencing an issue where paragraphs are being overwritten. My goal is to find a

Snippet of HTML: <div class="split left" > <div class="centered"> <div class="container"> <p>Hi!</p> </div> <div class="darker"> <p>{{message}}& ...

Use various cumxxx functions (such as sum, min, etc.) on a DataFrame with a window of changing size

Implementing a cumxxx operation on a variable-sized window within a DataFrame is the goal. Taking into account the provided inputs: import pandas as pd from random import seed, randint from collections import OrderedDict p5h = pd.period_range(start=&apos ...

Insufficient Memory: Not enough space available to allocate 3.33 GiB for an array containing (15500, 2, 240, 240, 1) elements of type int16

Running my code on the latest version of PyCharm, I am using a Windows 7 64-bit system with 16GB of RAM and... Python version: 3.7.7 (default, May 6 2020, 11:45:54) [MSC v.1916 64 bit (AMD64)] I am attempting to load numerous NIFTI images from the BraTS ...

Use Python to access a website button and download a xlsx file with just one click

Currently, I am working on a Python script to generate a daily COVID-19 dashboard for my country and state. Unfortunately, I have hit a roadblock in downloading one of the required files. To download this file, I need to visit the website () and click on ...

BeautifulSoup fails to detect tables within webpage

I am struggling to extract the data from the first table on a website. Despite attempting various solutions found here, I have been unsuccessful in locating the table and consequently retrieving the data within it. The methods I have tried are as follows: ...

Utilize Regex to isolate text between specified string markers

I am attempting to scrape a website and I need to extract the JSON data from the data variable in the JavaScript code below using Python Regex. <script type="text/javascript"> P.when('A').register("ImageBlockATF", function(A){ var data ...

Running Python code within Postgresql database

Is it possible to run text that is stored in a Postgresql database as Python code and have it update the database accordingly? ...

Improving performance of bigint operations

I've been working through the book 'Programming in D' to learn about the D programming language. Recently, I attempted to tackle a problem involving summing up the squares of numbers from 1 to 10000000. Initially, I employed a functional app ...

Transferring cookie data between requests in CrawlSpider

My current project involves scraping a bridge website to gather data from recent tournaments. I have previously asked for help on this issue here. Thanks to assistance from @alecxe, the scraper now successfully logs in while rendering JavaScript with Phant ...

Python implementation of the Velocity-Verlet algorithm for a double-well potential

Currently, I am working on implementing the Verlet algorithm to model a double well potential V(x) = x^4-20x^2 in order to create a basic phase portrait. However, the resulting phase portrait has an irregular oval shape and appears to be incorrect. I suspe ...

Converting a row to a column vector based on a particular condition in Python

In this code, positive values are selected from a matrix along with their corresponding indices. The current output shows these positive values in a row vector format. However, the desired output is to have the positive values presented in a column vector ...