多个数据集和拟合线

Multiple datasets and fit line

我有不同的数据集:

Df1 
X  Y
1  1
2  5
3  14
4  36
5  90

Df2

X  Y
1  1
2  5
3  21
4  38
5  67

Df3

X  Y
1  1
2  5
3  10
4  50
5  78

我想确定一条适合此数据的线并将所有数据绘制在一个图表中(如回归)。 在 x 轴上我有时间;在 y 轴上我有事件发生的频率。 关于如何确定直线和绘制结果并保持不同图例的方法的任何帮助(使用 seaborn 或 matplotlib 都可以)都会有所帮助。

到目前为止我所做的是绘制如下三行:

plot_df = pd.DataFrame(list(zip(dataset_list, x_lists, y_lists)),
               columns =['Dataset', 'X', 'Y']).set_index('Dataset', inplace=False)

plot_df= plot_df.apply(pd.Series.explode).reset_index() # this step should transpose the resulting df and explode the values

# plot
fig, ax = plt.subplots(figsize=(10,8))

for name, group in plot_df.groupby('Dataset'):
    group.plot(x = "X", y= "Y", ax=ax, label=name)

请注意,开头的三个列表包含三个不同df的信息。

我建议使用 scipy.stats 中的 linregress,因为这提供了非常易读的代码。只需要将逻辑添加到您的循环中:

from scipy.stats import linregress

for name, group in plot_df.groupby('Dataset'):
    group.plot(x = "X", y= "Y", ax=ax, label=name)
    
    #fit a line to the data
    fit = linregress(group.X, group.Y)
    
    ax.plot(group.X, group.X * fit.slope + fit.intercept, label=f'{name} fit')