Last active
November 3, 2023 15:14
-
-
Save tomron/8798256fcee5438edd58c17654adf443 to your computer and use it in GitHub Desktop.
A nicer seasonal decompose chart using plotly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from statsmodels.tsa.seasonal import seasonal_decompose | |
import plotly.tools as tls | |
def plotSeasonalDecompose( | |
x, | |
model='additive', | |
filt=None, | |
period=None, | |
two_sided=True, | |
extrapolate_trend=0, | |
title="Seasonal Decomposition"): | |
""" | |
Plot time series decomposition | |
:param x: Time series. | |
See documentation of the remaining models here - | |
https://www.statsmodels.org/stable/generated/statsmodels.tsa.seasonal.seasonal_decompose.html | |
Example - | |
import pandas as pd | |
from datetime import datetime | |
import PlotTimeSeries | |
s = pd.DataFrame(list(range(1, 11))*10, | |
index=pd.date_range(start=datetime(2010, 1, 1), periods=100)) | |
fig = PlotTimeSeries.plotSeasonalDecompose(s) | |
fig.show() | |
""" | |
result = seasonal_decompose( | |
x, model=model, filt=filt, period=period, | |
two_sided=two_sided, extrapolate_trend=extrapolate_trend) | |
fig = make_subplots( | |
rows=4, cols=1, | |
subplot_titles=["Observed", "Trend", "Seasonal", "Residuals"]) | |
fig.add_trace( | |
go.Scatter(x=result.seasonal.index, y=result.observed, mode='lines'), | |
row=1, col=1, | |
) | |
fig.add_trace( | |
go.Scatter(x=result.trend.index, y=result.trend, mode='lines'), | |
row=2, col=1, | |
) | |
fig.add_trace( | |
go.Scatter(x=result.seasonal.index, y=result.seasonal, mode='lines'), | |
row=3, col=1, | |
) | |
fig.add_trace( | |
go.Scatter(x=result.resid.index, y=result.resid, mode='lines'), | |
row=4, col=1, | |
) | |
return fig |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@chrimaho
i have modified your code that it takes a dataframe to plot multiple columns decompostion side by side