'MatplotLib/Pandas Using Time as X Axis

I am working on a project where I would like to read sensor data from a CSV file and do a live graph. I am using Matplotlib for the graphing and Pandas for the data handling.

For the CSV I am using:

  • Column 0= Pass/Fail Boolean
  • Column 1= Time in %h:%m:%s format.
  • Column 3= Error Code (int64)

When I run the script I get a "ValueError: values must be a 1D array". I believe its coming from the time data, but when i check the dtype it is a datetime64 as expected. My program is below:

from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

index = count()


    def animate(i):
    # Use Pandas to Read CSV and create a Dataframe. Use KWARGS to choose columns, and then 
      specify name and type of data.
    data = pd.read_csv('C:/Python/20220124.csv',usecols=[0, 1, 3], names=["Pass", "Time", 
      "Error Code"], header= None, parse_dates=[1], dtype={"Pass": 'boolean', "Error Code": 
      'Int64'})
    pd.to_datetime(data['Time'])
    y1 = data['Pass']
    x1 = data['Time']
    y2 = data['Error Code']

    # Pyplot Clear Axes
    plt.cla()

    #Pyplot Plot data in line graphs
    plt.plot(x1, y1, label='Pass/Fail', lw=3, c='c', marker='o', markersize=4, mfc='k')
    plt.plot(x1, y2, label='Error Code', lw=2, ls='--', c='k')

    plt.legend(loc='upper left')
    plt.tight_layout()

    #Pyplot Get Current Axes
    ax = plt.gca()



ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.tight_layout()
plt.show()


Solution 1:[1]

You can do this using only pandas. Pandas also contain a pre-built function for visualization :

df = data[['Error Code', 'Time']] # Create a pandas series contain the data that will be ploted
df.set_index('Time', inplace = True) # set the time as an index (it will serve as x-axis)
df.plot() # plot the graph

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1