0

I am pretty new to this stuff so I apologize in advance for asking what might be a a very basic question. What I am doing is plotting a graph using matplotlib from a csv file that has the timestamps and voltage values from a sensor. The problem I am facing is that the x-axis in the plotted graph is unreadable as can be seen in the picture with the plot. I would be grateful if anyone could point me in the right direction on how to make the axis more readable while using the current format that I have. Please find attached the code for generating this plot. In other examples that I have found it is more common to see people plotting timestamps using the datetime module into the graph. In my case I have set the format for the timestamps in the script I wrote to generate the csv file with the sensor data and time.

Thank you for your time.

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

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

#index = count()

def animate(i):
    data = pd.read_csv('/home/pi/musselmonitor/hall_readings.csv')
    #print(data.values)
    x_vals = [item[1]for item in data.values] 
    y_vals = [item[2]for item in data.values]

    
    plt.cla()
    plt.plot(x_vals, y_vals, label = 'Voltage over time')
    plt.xticks(rotation = 25)
    plt.autoscale(enable=True, axis='both', tight = None)
    plt.xlabel('Time')
    plt.ylabel('Voltage in mV')
    plt.legend(loc = 'upper left')
    plt.tight_layout()



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

plt.grid()
plt.tight_layout()
plt.show()

1 Answer 1

1

The basic idea of animating a graph is to animate the data to be used according to the number of frames, so first set the basic shape of the graph as the initial value. Then update the data within the animation function. I haven't set a special display format for the x-axis since I'm not sure if your tetas are in date/time format or string. Depending on your data, you may need to use locator& fomatter. See here for more information.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

plt.style.use('fivethirtyeight')

date_rng = pd.date_range('2021-07-14', freq='1s', periods=300)
voltage = [np.random.uniform(0,1)+14 for n in range(300)]
df = pd.DataFrame({'timestamp':pd.to_datetime(date_rng, format='%H:%M%:%S'), 'voltage':voltage})

fig,ax = plt.subplots()

ax.set(xlim=(df['timestamp'].min(),df['timestamp'].max()), ylim=(14.0, 15.0))
line, = ax.plot([], [], 'b-', lw=3, label='Voltage over time')

ax.set_xlabel('Time')
ax.set_ylabel('Voltage in mV')
ax.grid()

def animate(i):
    line.set_data(df.loc[:i,'timestamp'], df.loc[:i,'voltage'])
    plt.setp(ax.get_xticklabels(), rotation=25, ha='right')

ani = FuncAnimation(fig, animate, frames=300, interval=100, repeat=False)

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

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

If you still have issues with the display format of the x-axis, please comment. If my answer was helpful to you, please click the check mark and accept it as the correct answer.
Thanks for your answer. It definitely provided me with some better insight on how to to approach the problem I am dealing with. However, like I mention in my post my issue was that data from the csv file was not displaying properly. Specifically the time data with the %H:%M%:%S format was not being displayed. Unfortunately, I could not use the timestamp as it is used in your code as the timestamps I am getting are directly linked with the voltage being generated and stored in the csv file. Regardless, I appreciate your help nonetheless. Thank you.
I responded by creating toy data since the contents of the csv file were not presented to me. So if your data is presented in a publishable way, the problem may be solved. Also, I think your code has a csv file read in the animation function and is using all of that data to animate. As it is, it seems to me that you are displaying a graph with all the data displayed repeatedly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.