Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

seaborn lineplot time-series indicating trend in activity

On a seaborn lineplot, I would like to indicate trend in a time-series data, preferably using different colours.

For example, taking this fake data:

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=50), columns=['max'])
df['day'] = pd.date_range('2016-1-1', periods=50, freq='SMS')#freq='W')
df['date'] = df['day'].dt.strftime('%Y-%m')

On a lineplot this produces the following figure:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sns.lineplot(data=df, x = df['date'], y='max', )
plt.xticks(rotation=45)

enter image description here

So I would like to indicate the trend in time series between 2017-01 and 2017-08 such that the plot’s background in this area is in green, with begin and end marked (similar to the figure below, but inserting green background in the area indicated).
enter image description here

>Solution :

You can use ax.axvspan:

ax = sns.lineplot(data=df, x = df['date'], y='max', )
ax.axvspan('2017-01', '2017-08', color='g', alpha=0.1)

output:

enter image description here

alternative with a different zorder:

ax.axvspan('2017-01', '2017-08', color='g', alpha=0.5, zorder=0)

output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading