Reputation: 1
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()
Upvotes: 0
Views: 900
Reputation: 35205
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()
Upvotes: 1