Skip to content

Instantly share code, notes, and snippets.

@jaradc
Last active December 21, 2017 09:44
Show Gist options
  • Save jaradc/b872041e13a927167480823abd198c94 to your computer and use it in GitHub Desktop.
Save jaradc/b872041e13a927167480823abd198c94 to your computer and use it in GitHub Desktop.
This lets you create subplots of n rows and 1 column of a metric within a time series.
def ma_subplots(df, window, title=None):
fig, ax = plt.subplots(df.shape[1], 1, figsize=(12, 7))
ax = ax.ravel()
for i,col in enumerate(df):
mean = df[col].mean()
ma = df[col].rolling(window).mean()
mstd = df[col].rolling(window).std()
ax[i].plot(df.index, df[col], color='k', label=col)
ax[i].plot(ma.index, ma, 'b', label='Moving Avg.')
ax[i].fill_between(mstd.index, ma - 2*mstd, ma + 2*mstd, color='b', alpha=0.2)
ax[i].hlines(mean, df.index.min(), df.index.max(), linestyle=':')
ax[i].margins(0)
ax[i].set_yticks(list(ax[i].get_yticks()) + [mean.round(2)])
ax[i].legend(loc='best')
ax[i].grid(linewidth=1, color='lightgray', alpha=0.5)
if title is not None:
plt.suptitle(title)
plt.tight_layout()
plt.subplots_adjust(top=0.95)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment