adding legend to lineplot according to maplotlib's axvspan

Issue

OK, I have this line plot of data trend over this period.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(np.random.randint(100, size=25), columns=['max'])
df['day'] = pd.date_range('2021-1-1', periods=25, freq='SMS')#freq='W')
df['date'] = df['day'].dt.strftime('%Y-%m')

plt.figure(figsize=(10,6))
ax = sns.lineplot(data=df, x = df['date'], y='max', )
ax.axvspan('2021-03', '2021-06', color='g', alpha=0.2)
ax.axvspan('2021-06', '2021-09', color='b', alpha=0.3)
ax.axvspan('2021-09', '2021-12', color='m', alpha=0.5)
plt.xticks(rotation=45)

Figure:
enter image description here

But I want to add legend corresponding to each period (coloured) covereds, such that:

  • 2021-03 to 2021-06 the green area bears the legend spring,
  • 2021-06 to 2021-09 blue area is legend summer, and
  • 2021-09 to 2021-12 (magenta) legend winter.

Solution

You can specify a label in the axvspans:

ax.axvspan('2021-03', '2021-06', color='g', alpha=0.2, label='Spring')
ax.axvspan('2021-06', '2021-09', color='b', alpha=0.3, label='Summer')
ax.axvspan('2021-09', '2021-12', color='m', alpha=0.5, label='Winter')
ax.legend()

enter image description here

Answered By – Stef

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published