Right now, I have written a code that gives me a meteogram that I'm happy with, but it only does it for 1/1/1987 given how I've defined "left" and "right" and used them as x-boundaries:
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
IAH = pd.read_excel('IAH.xlsx')
x = list(IAH['valid'])
y1 = list(IAH['tmpf'])
y2 = list(IAH['dwpf'])
y3 = list(IAH['drct'])
y4 = list(IAH['mslp'])
left = dt.datetime(1987, 1, 1, 0, 0, 0)
right = dt.datetime(1987, 1, 1, 23, 59, 59)
fig, ax = plt.subplots(3)
ax[0].plot(x, y1, color='blue')
ax[0].plot(x, y2, color='green')
ax[0].set_xbound(left, right)
ax[0].set_ybound(0, 100)
ax[0].set_ylabel('TMP & DP')
ax[0].xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
ax[1].plot(x, y3, color='black', marker='o')
ax[1].set_xbound(left, right)
ax[1].set_ybound(0, 360)
ax[1].set_ylabel('WDIR')
ax[1].xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
ax[2].plot(x, y4, color='red')
ax[2].set_xbound(left, right)
ax[2].set_ybound(1000, 1040)
ax[2].set_ylabel('MSLP')
ax[2].xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.figure()
fig.tight_layout()
plt.show()
How can I turn this into a loop that will save the created figure for each day in the time series being used?
I'm thinking I should do something additional like this:
start_date = dt.datetime(1987, 1, 1)
end_date = dt.date(2021, 12, 31)
delta = dt.timedelta(days=1)
and then use a while loop, but I'm new to Python and having trouble getting there.
If you add a timedelta
object to a datetime
object it will result in another datetime
object with the timedelta
time added:
>>> dt.datetime(1987, 1, 1) + dt.timedelta(days=1)
datetime.datetime(1987, 1, 2, 0, 0)
>>> dt.datetime(1987, 1, 1) + dt.timedelta(days=15)
datetime.datetime(1987, 1, 16, 0, 0)
>>> dt.datetime(1987, 1, 1) + dt.timedelta(days=50)
datetime.datetime(1987, 2, 20, 0, 0)
Also you can compare two datetime
objects to know which one is greater, lower or equal than another:
>>> date_one = dt.timedelta(1987, 1, 10)
>>> date_two = dt.timedelta(1987, 1, 15)
>>> date_one > date_two
False
>>> date_two > date_one
True
With this we can write a while
loop to cycle over a desired range of dates:
>>> start_date = dt.datetime(1987, 1, 1)
>>> end_date = dt.datetime(1987, 1, 5)
>>> delta = dt.timedelta(days=1)
>>> current_date = start_date
>>> while current_date < end_date:
... print("Cycling with date:", current_date)
... current_date = current_date + delta
...
Cycling with date: 1987-01-01 00:00:00
Cycling with date: 1987-01-02 00:00:00
Cycling with date: 1987-01-03 00:00:00
Cycling with date: 1987-01-04 00:00:00
Given said all that, you can put all your code inside a function that receives two datetime
objects, start
and end
, cycle over them day by day using a timedelta(days=1)
object and show
the results one by one, then you can evolve you code from that point.
Hope this helps.