OK, I have this line plot of data trend over this period.
JavaScript
x
16
16
1
import pandas as pd
2
import numpy as np
3
import matplotlib.pyplot as plt
4
import seaborn as sns
5
6
df = pd.DataFrame(np.random.randint(100, size=25), columns=['max'])
7
df['day'] = pd.date_range('2021-1-1', periods=25, freq='SMS')#freq='W')
8
df['date'] = df['day'].dt.strftime('%Y-%m')
9
10
plt.figure(figsize=(10,6))
11
ax = sns.lineplot(data=df, x = df['date'], y='max', )
12
ax.axvspan('2021-03', '2021-06', color='g', alpha=0.2)
13
ax.axvspan('2021-06', '2021-09', color='b', alpha=0.3)
14
ax.axvspan('2021-09', '2021-12', color='m', alpha=0.5)
15
plt.xticks(rotation=45)
16
But I want to add legend corresponding to each period (coloured) covereds, such that:
2021-03
to2021-06
the green area bears the legend spring,2021-06
to2021-09
blue area is legend summer, and2021-09
to2021-12
(magenta) legend winter.
Advertisement
Answer
You can specify a label
in the axvspan
s:
JavaScript
1
5
1
ax.axvspan('2021-03', '2021-06', color='g', alpha=0.2, label='Spring')
2
ax.axvspan('2021-06', '2021-09', color='b', alpha=0.3, label='Summer')
3
ax.axvspan('2021-09', '2021-12', color='m', alpha=0.5, label='Winter')
4
ax.legend()
5