在Python中绘制趋势线

时间:2020-10-29 16:29:30

标签: python matplotlib seaborn overlap

我想在数据图的顶部绘制趋势线。这必须很简单,但我无法弄清楚如何实现。

让我们说我有以下内容:

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()

结果图为:

enter image description here

我要添加的是趋势线。类似于下面的红线:

enter image description here

感谢您的反馈。

2 个答案:

答案 0 :(得分:3)

移动平均线是一种方法(我的第一个想法已经提出)。

另一种方法是使用多项式拟合。由于您的原始数据中有100点,因此在下面的示例中,我选择了10阶拟合(数据长度的平方根)。对原始代码进行一些修改:

idx = [i for i in range(100)]
rnd = np.random.randint(0,100,size=100)
ser = pd.Series(rnd, idx)

fit = np.polyfit(idx, rnd, 10)
pf = np.poly1d(fit)

plt.plot(idx, rnd, 'b', idx, pf(idx), 'r')

此代码提供了如下图:

Source

答案 1 :(得分:2)

您可以使用滚动平均值执行以下操作:

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

您还可以做一个回归图来分析如何使用以下方法插值数据:

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

enter image description here