Home > Back-end >  adding legend to lineplot according to maplotlib's axvspan
adding legend to lineplot according to maplotlib's axvspan

Time:06-10

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.

CodePudding user response:

You can specify a label in the enter image description here

  • Related