Search code examples
pythonmatplotlibseaborn

Overlay Shaded Regions on a Line Plot Based on Conditions


I would like to plot a line plot and make different overlay based on condition as illustrated below.

enter image description here

May I know how, or if possible, please kindly redirect me to right material on achieving the intended objective.

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
rng = np.random.default_rng(2)
mlist=[]
for _ in range(4):

    m=np.random.rand(4).tolist()
    n=rng.integers(0, 6, size=(1)).tolist()*4
    df = pd.DataFrame(zip(m,n), columns=['yval','type'])
    mlist.append(df)

df=pd.concat(mlist).reset_index(drop=True).reset_index()
sns.lineplot(data=df, x="index", y="yval")
plt.show()

Suggestion using Matplotlib or Seaborn, or any other package are welcome


Solution

  • The filling of the section was achieved using axvspan. I also used text for annotations.

    The line is plotted with sns.lineplot, but can also be implemented with either of the following:

    • ax = df.plot(y='yval')
    • fig, ax = plt.subplots() and ax.plot('index', 'yval', data=df)
    import numpy as np
    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    # Create Sample Data
    np.random.seed(0)
    rng = np.random.default_rng(2)
    
    m = np.random.rand(16)
    n = np.repeat(rng.integers(0, 6, size=4), 4)
    df = pd.DataFrame({'index': range(len(m)), 'yval': m, 'type': n})
    
    # Plot the line
    ax = sns.lineplot(data=df, x="index", y="yval")
    
    # Add the overlay spans and annotations
    overlay = {0: 'm', 1: 'gray', 5: 'r'}
    
    for i in np.arange(0, len(df), 4):
        tmp = df.iloc[i:i+4, :]
        v = overlay.get(tmp.type.unique()[0])
        ax.axvspan(min(tmp.index), max(tmp.index)+1, color=v, alpha=0.3)
        ax.text(((min(tmp.index)+max(tmp.index)+1) / 2)-1, 0.1, f'type {tmp.type.unique()[0]}', fontsize=12)
    
    plt.show()
    

    enter image description here