Search code examples
pythonmatplotlibseabornoverlap

Plotting tendency line in Python


I want to plot a tendency line on top of a data plot. This must be simple but I have not been able to figure out how to get to it.

Let us say I have the following:

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

df = pd.DataFrame(np.random.randint(0,100,size=(100, 1)), columns=list('A'))
sns.lineplot(data=df)

ax.set(xlabel="Index",
       ylabel="Variable",
       title="Sample")

plt.show()

The resulting plot is:

enter image description here

What I would like to add is a tendency line. Something like the red line in the following:

enter image description here

I thank you for any feedback.


Solution

  • You can do something like this using Rolling Average:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    data  = np.random.randint(0,100,size=(100, 1))
    
    df["rolling_avg"] = df.A.rolling(7).mean().shift(-3)
    
    sns.lineplot(data=df)
    
    plt.show()
    

    enter image description here

    You could also do a Regression plot to analyse how data can be interpolated using:

    ax = sns.regplot(x=df.index, y="A", 
                     data=df,
                     scatter_kws={"s": 10},
                     order=10, 
                     ci=None)
    

    enter image description here