0

I want to plot a time series on top of a coloured background that show when the winter period is.

dates = pd.date_range("2000-01-01", "2004-01-01", freq="D")
df = pd.DataFrame({"y": np.random.random(len(dates))}, index=dates)

f, ax = plt.subplots(figsize=(12, 4))
ax.plot(df.index, df["y"])

enter image description here

I want to guide the eye by highlighting the winter periods ("DJF")

Tommy Lees
  • 1,293
  • 3
  • 14
  • 34

1 Answers1

0

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)

Plot with background polygons

Tommy Lees
  • 1,293
  • 3
  • 14
  • 34