Using a combination of the consecutive function defined by this SO answer and the overplotting background polygons SO answer here we can acheive the stated goals.
We use the ax.axvspan
function to plot a span between X1: X2
f, ax = plt.subplots(figsize=(12, 4))
ax.plot(df.index, df["y"])
# plot winter spans in background
# calculate days that are in the winter season (DJF)
# 0 = DJF, 1 = MAM, 2 = JJA, 3 = SON
is_winter = (df.reset_index()["index"].dt.month % 12 // 3) == 0
winter_time_indexes = np.argwhere(is_winter.values).flatten()
def consecutive(data, stepsize=1):
# https://stackoverflow.com/a/7353335/9940782
return np.split(data, np.where(np.diff(data) != stepsize)[0] + 1)
# calculate each consecutive index as a winter period
winters = consecutive(winter_time_indexes)
for winter in winters:
time_min, time_max = df.index.values[winter.min()], df.index.values[winter.max()]
ax.axvspan(time_min, time_max, facecolor='C3', alpha=0.5)
