Skip to content

Instantly share code, notes, and snippets.

@jeasinema
Last active February 26, 2019 08:15
Show Gist options
  • Save jeasinema/e981d896de0908d0569908b07a579e7e to your computer and use it in GitHub Desktop.
Save jeasinema/e981d896de0908d0569908b07a579e7e to your computer and use it in GitHub Desktop.
Plot smooth curve like other people do
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def smooth(y, box_pts):
box_pts = max(box_pts, 1) if len(y) > box_pts else 1
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='valid')
return y_smooth
repeat = 5
length = 1000
tag_list = [
'Plot A',
'Plot B',
'Plot C'
]
value_list = [
('Model 1', np.random.rand(len(tag_list), repeat, length)),
('Model 2', np.random.rand(len(tag_list), repeat, length)),
('Model 3', np.random.rand(len(tag_list), repeat, length)),
('Model 4', np.random.rand(len(tag_list), repeat, length)),
]
fontsize = 13
title = 'Demo'
def main():
fig = plt.figure()
fig.set_size_inches(15, 5)
fig.clf()
num_plots = len(tag_list)
clrs = sns.color_palette("husl", len(value_list))
base = fig.add_subplot(111)
base.spines['top'].set_color('none')
base.spines['bottom'].set_color('none')
base.spines['left'].set_color('none')
base.spines['right'].set_color('none')
base.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
with sns.axes_style('darkgrid'):
axes = fig.subplots(1, num_plots)
for ind_model, item in enumerate(value_list):
k, v = item
values_list = v
for ind, (tag, values) in enumerate(zip(np.array(tag_list), np.array(values_list))):
a_min = np.iinfo(np.int64).min
a_max = np.iinfo(np.int64).max
# when extra smoothness is needed for each repeated runnings
tmp = []
win_size = 10 # critic
for i in values:
tmp.append(smooth(i, win_size))
tmp = np.array(tmp)
mean = np.mean(tmp, axis=0)
std = np.std(tmp, axis=0)
# when there is no need for extra smoothness
# mean = np.mean(values, axis=0)
# std = np.std(values, axis=0)
axes[ind].plot(np.arange(len(mean)), mean, '-', c=clrs[ind_model], label=k.upper())
axes[ind].fill_between(np.arange(len(mean)), np.clip(mean - std, a_min=a_min, a_max=a_max),
np.clip(mean + std, a_min=a_min, a_max=a_max), alpha=0.3, facecolor=clrs[ind_model])
axes[ind].set_ylabel(tag, fontsize=fontsize)
axes[-1].legend(fontsize=fontsize, loc=4) # inplot
# axes[-1].legend(fontsize=fontsize, loc='center left', bbox_to_anchor=(1, 0.5)) # right side
# axes[-1].legend(fontsize=fontsize, loc='center left', bbox_to_anchor=(0.5, -0.05)) # down side(not working yet)
base.set_title(title, fontsize=fontsize)
base.set_xlabel('Trials', fontsize=fontsize)
fig.tight_layout(pad=0)
fig.savefig('{}.pdf'.format(title))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment