如何使用 Seaborn 的 FacetGrid 在每个图(时间序列的趋势)上添加不同的线

How to add a different line on each plot (trend of a time series) using Seaborn's FacetGrid

我想画这样的图(自行车在不同地方的时间序列):

但要在此图上添加每个时间序列的趋势。

就像这里解释的那样:,但是每张图都有不同的线,所以我没有做到像他们那样。


上下文:

我的数据是这样的:

    date        lieu                        nombre
0   2016-05-01  Avenue Gambetta             14.000
1   2016-05-01  Avenue Gaston Berger        2.625
2   2016-05-01  Avenue Victor Hugo          5.000
3   2016-05-01  Avenue de la République     5.250
4   2016-05-01  Avenue des Belges           5.875

我用这段代码绘制了第一张图(上图):

g = sns.FacetGrid(data, col="lieu", col_wrap=4, hue_kws={"ls":["--"]})
g.map(plt.plot, "date", "nombre")

通过旋转我的数据,我得到了这些时间序列:

ts

lieu    Avenue Gambetta     Avenue Gaston Berger    Avenue Victor Hugo  Avenue de l'Europe
date                
2016-09-01  15.5    3.500   4.25    2.750
2016-10-01  8.0     3.750   3.25    3.750
2016-11-01  7.5     1.875   3.75    3.250
2016-12-01  9.5     1.125   4.00    1.125
2017-01-01  4.5     1.250   4.00    2.000

然后我计算了时间序列的趋势:

ts_decompose = seasonal_decompose(ts, model='additive',freq=12)
ts_decompose.trend.iloc[5:10]

lieu    Avenue Gambetta     Avenue Gaston Berger    Avenue Victor Hugo  Avenue de l'Europe
date                
2017-02-01  8.9625  2.77500     3.7875  2.87500
2017-03-01  9.0750  2.69375     4.0750  3.09375
2017-04-01  9.3750  2.68125     4.3375  3.16875
2017-05-01  9.3250  2.75000     4.3125  3.24375
2017-06-01  9.3375  2.81250     4.2375  3.33125

但我没有找到如何在我的第一张图表上添加趋势线(我没有使用 facetgrid,但没有)。 你有什么想法可以帮助我吗?

谢谢!

可能有更简单的方法,但您可以通过先创建多个轴并在您想要的轴上绘制每个函数来手动完成。所以你首先要创建四个轴:

fig, axs = plt.subplots(ncols=4)

然后对第一个轴做这样的事情(我不确定你的数据是如何构建的,基本上使用你的原始数据作为第一个图的原始数据,在同一轴上使用第二个图的趋势数据:

sns.plot(x='lieu', y='nombre', data=data[data['lieu']=='Avenue Gambetta'], ax=axs[0])
sns.plot(x='lieu', y='trend', data=trenddata[trenddata['lieu']=='Avenue Gambetta'], ax=axs[0])

然后 axs[1] 换个地方等等