Search code examples
pythontime-seriesseabornfacet-grid

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


I want to draw graphs like this (time series of bike counts on different places) :

but to add on this graph the trend of each time series.

Like explained here : How to add a comparison line to all plots when using Seaborn's FacetGrid, but with a different line on each graph, so I didn't achieve to do like them.


Context :

My data look like this :

    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

and I draw this first graph (above) with this code :

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

By pivoting my data, I get these time series :

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

And I computed the trends of the time series with :

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

But I don't find how to add lines with the trends on my first graph (I achieve without facetgrid, but not with). Have you an idea to help me ?

Thank you !


Solution

  • There may be an easier way but you can just do it manually by creating multiple axes first and plotting each function on the axis you desire. So you would first create four axes:

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

    And then for the first axis do something like this (I am not sure how your data is structured basically use your original data for the first plot and trend data for the second plot on the same axis:

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

    and on with axs[1] with a different lieu, etc.