Created
August 14, 2019 11:36
-
-
Save sjpfenninger/185bfc63ee51cf22fe65229dd722ebec to your computer and use it in GitHub Desktop.
Plot filled area charts to visualise distribution in time series data
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
MIT License | |
Copyright (c) 2019 Stefan Pfenninger | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. |
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
import matplotlib.pyplot as plt | |
import matplotlib.colors as mcolors | |
import matplotlib.patches as mpatches | |
import seaborn as sns | |
def draw_areas(df, legend=True, ax=None, pal=None, lw=2.5, alpha=1.0, only_one=False, **kwargs): | |
if not pal: | |
pal = sns.color_palette("Reds_r") | |
data = df.describe().T | |
data['90%'] = df.quantile(0.9) | |
data['10%'] = df.quantile(0.1) | |
data = data.rename(columns={'50%': 'Median'}) | |
ax = data.loc[:, 'Median'].plot( | |
lw=lw, | |
color=mcolors.colorConverter.to_rgb(pal[0]), | |
alpha=alpha, ax=ax) | |
if only_one: | |
ax.fill_between(range(len(data)), data['25%'], data['75%'], color=pal[2], alpha=alpha) | |
else: | |
ax.fill_between(range(len(data)), data['min'], data['max'], color=pal[3], alpha=alpha) | |
ax.fill_between(range(len(data)), data['10%'], data['90%'], color=pal[2], alpha=alpha) | |
ax.fill_between(range(len(data)), data['25%'], data['75%'], color=pal[1], alpha=alpha) | |
# Add legend entries | |
if only_one: | |
ax.add_patch(plt.Rectangle((0, 0), 0, 0, facecolor=pal[2], alpha=alpha, label='25% - 75%')) | |
else: | |
ax.add_patch(plt.Rectangle((0, 0), 0, 0, facecolor=pal[0], alpha=alpha, label='25% - 75%')) | |
ax.add_patch(plt.Rectangle((0, 0), 0, 0, facecolor=pal[1], alpha=alpha, label='10% - 90%')) | |
ax.add_patch(plt.Rectangle((0, 0), 0, 0, facecolor=pal[2], alpha=alpha, label='Min - Max')) | |
if legend: | |
leg = ax.legend( | |
loc='lower center', | |
bbox_to_anchor=(0, 0.85, 1, 1), | |
ncol=4) | |
leg.draw_frame(False) | |
ax.xaxis.get_major_ticks()[0].label1.set_visible(False) | |
return ax | |
def downsample_df_with_mean(df, freq): | |
s = (df.index.to_series() / freq).astype(int) | |
return df.groupby(s).mean() | |
def plot(series, palette=None, ax=None, freq='1D', resample=True, only_one=False, full_monthly_labels=True, **kwargs): | |
"""`series` is a pandas.Series with hourly data.""" | |
df = series.to_frame() | |
if resample: | |
df = df.resample(freq).mean() | |
# Get rid of Feb 29 | |
df = df[~((df.index.month == 2) & (df.index.day == 29))] | |
df.columns = ['data'] | |
df['Year'] = df.index.year | |
df['HourOfYear'] = ((df.index.dayofyear - 1) * 24) + df.index.hour | |
df_plot = df.pivot(values='data', columns='Year', index='HourOfYear') | |
df_plot.index.name = None | |
freqs = { | |
'1D': 24, | |
'7D': 168, | |
'1W': 168, | |
'1M': 720, | |
} | |
df_plot = downsample_df_with_mean(df_plot, freqs[freq]) | |
# Reindex to integer | |
df_plot.index = list(range(len(df_plot))) | |
ax = draw_areas(df_plot.T, pal=palette, ax=ax, only_one=only_one, **kwargs) | |
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] | |
if freq == '1D': | |
xticks = [0, 31, 59, 90, 120, 151, 181, 212, 242, 273, 303, 334] | |
xlabels = months | |
xticks_minor = xlabels_minor = None | |
elif freq == '1W' or freq == '7D': | |
xticks = [i / 7 for i in [0, 31, 59, 90, 120, 151, 181, 212, 242, 273, 303, 334]] | |
xlabels = months | |
xticks_minor = xlabels_minor = None | |
elif freq == '1M': | |
if full_monthly_labels: | |
xticks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] | |
xlabels = months | |
xticks_minor = xlabels_minor = None | |
else: | |
xticks = [0, 3, 6, 9] | |
xlabels = ['Jan', 'Apr', 'Jul', 'Oct'] | |
xticks_minor = [1, 2, 4, 5, 7, 8, 10, 11] | |
xlabels_minor = [''] * len(xticks_minor) | |
ax.set_xticks(xticks) | |
ax.set_xticklabels(xlabels) | |
if xticks_minor: | |
ax.set_xticks(xticks_minor, minor=True) | |
ax.set_xticklabels(xlabels_minor, minor=True) | |
for label in ax.get_xticklabels(): | |
label.set_visible(True) | |
ax.set_xlabel(None) | |
return ax |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment