Fill between mean and curve fluctuations using matplotlib?

Viewed 186

How can we plot a curve where we have multiple realization of it like the following picture. enter image description here

My try: I have tried to create something that mimics the curves in the above pictures.

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(10)
x = np.repeat(np.linspace(0,10, 10)[np.newaxis,...], 5, axis=0)
s = np.diag(np.array([0.05, 0.1, 0.3, 0.01, 0.2]))
y =  1- np.sqrt(x) + np.matmul(np.diag(np.array([0.05, 0.1, 0.3, 0.01, 0.2])),np.random.randn(x.shape[0],x.shape[1]))
fig, ax = plt.subplots()
for i in range(5):
  ax.plot(x[i,:],y[i,:])
plt.show()

I do not how to go further.

Note: The five curves in the below picture should be converted to one curve that has its mean in the middle and is overshadowed by the fluctuations.

enter image description here

1 Answers

generate the entities you want to plot (mean and fluctuation courves), then plot them.

Use matplotlib.pyplot.fill_between to fill the area between two curves.

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(10)
x = np.repeat(np.linspace(0,10, 10)[np.newaxis,...], 5, axis=0)
s = np.diag(np.array([0.05, 0.1, 0.3, 0.01, 0.2]))
y =  1- np.sqrt(x) + np.matmul(np.diag(np.array([0.05, 0.1, 0.3, 0.01, 0.2])),np.random.randn(x.shape[0],x.shape[1]))

for i in range(5):
  plt.plot(x[i,:],y[i,:], ms=4, marker='o')

y_mean = np.mean(y, axis=0)
y_std = np.std(y, axis=0)
y_std_up = y_mean + y_std
y_std_low = y_mean - y_std
print(y_mean.shape)

plt.plot(x[0,:], y_mean, 'k' , ms=4, marker='o')
plt.fill_between(x[0,:], y_std_low,y_std_up, alpha=.5, color='k', lw=0)

enter image description here

Related