I've been looking all over for a way to evenly space dates using Python 3 with matplotlib, and I haven't been able to find anything that would apply to just having a list of datetime objects.
I'm trying to plot data over a certain time interval. This time interval could vary from a few minutes to multiple weeks. If I have a list of data, and a corresponding list of datetime objects (in string form), how can I automatically format (and plot) the dates using the matplotlib library? I want to make sure that the ticks are evenly spaced, make sense for the total time range, and aren't overcrowded.
Here is my code:
# imports
import csv
import matplotlib.pyplot as plt
import datetime
# store rows
rows = []
# read data
with open('weatherSoilData.csv', newline='') as csvFile:
reader = csv.reader(csvFile, delimiter=',')
for row in reader:
rows.append(row)
# get rid of header
rows.pop(0)
# create column lists
dates = []
soilTemperatures = []
# loop through columns and create lists of the column values
for i in range(2):
# handle dates
if not i:
for row in rows:
dates.append(row[i])
else:
for row in rows:
soilTemperatures.append(float(row[i]))
# display data
plt.plot(dates, soilTemperatures)
plt.title("Time vs. Soil Temperature")
plt.xlabel("Time")
plt.ylabel("Soil Temperature (degrees C)")
plt.xticks(rotation=90)
plt.ylim(-30, 50)
plt.show()
Here is a short bit of the .csv file:
date,soilTemperature(degrees C)
2023-09-25 17:38:48.761035,21.375
2023-09-25 17:38:51.562840,21.375
2023-09-25 17:38:54.362466,21.375
2023-09-25 17:38:57.161336,21.312
2023-09-25 17:38:59.960572,21.312
2023-09-25 17:39:02.762784,21.375
Your date/time values aren't datetime objects. They're simply strings, hence, matplotlib doesn't consider them dates. You need to convert each of these string to datetime objects, then, matplotlib will treat them correctly.
Try the following:
for row in rows:
dates.append(datetime.datetime.strptime(row[i], "%Y-%m-%d %H:%M:%S.%f"))
You may need to fool around with the x axis ticks to get the format you want.