Skip to content

Instantly share code, notes, and snippets.

@dsalaj
Created November 13, 2019 08:06
Show Gist options
  • Save dsalaj/1178f173bbc2ab56e5199442b732252d to your computer and use it in GitHub Desktop.
Save dsalaj/1178f173bbc2ab56e5199442b732252d to your computer and use it in GitHub Desktop.
Calculate mean of list of arrays with different lengths (useful for plotting progress of incomplete simulation runs)
import numpy as np
x = [1, 2, 3.5, 4]
y = [1, 2, 3, 3, 4, 5, 3]
z = [7, 8]
arrs = [x, y, z]
def tolerant_mean(arrs):
# arrs = [x, y, z]
lens = [len(i) for i in arrs]
arr = np.ma.empty((np.max(lens),len(arrs)))
arr.mask = True
for idx, l in enumerate(arrs):
arr[:len(l),idx] = l
return arr.mean(axis = -1), arr.std(axis=-1)
y, error = tolerant_mean(arrs)
x = np.arange(len(y))+1
from matplotlib import pyplot as pl
fig, ax = pl.subplots(figsize=(4, 3.5))
ax.plot(x, y)
ax.fill_between(x, y-error, y+error, alpha=0.3)
pl.tight_layout()
pl.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment