'Calculating standard deviation (Python)
I calculated the mean of every nth element from 4 lists like in this example below. I would like to caluculate the standard deviation from that and add it as error bars to my plot
y1 = [1, 2, 2, 4, 5]
y2 = [3, 6, 9, 12, 0]
y3 = [2, 3, 4, 5, 6]
y4 = [2, 1, 5, 7, 9]
average = np.array([y1, y2, y3, y4]).mean(axis=0)
y = average.tolist()
plot(x,y)
How can I do that?
Solution 1:[1]
To address your first question, you can calculate the standard deviation in much the same way as you are currently calculating the average. Numpy has a std function which takes similar arguments to mean.
std_dev = np.array([y1, y2, y3, y4]).std(axis=0)
For the second question, assuming that plot(x,y) is from matplotlib.pyplot, you could instead use errorbar, which takes an extra yerr argument which lets you specify your error bars.
A full example script:
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 3, 4]
y1 = [1, 2, 2, 4, 5]
y2 = [3, 6, 9, 12, 0]
y3 = [2, 3, 4, 5, 6]
y4 = [2, 1, 5, 7, 9]
datasets = np.array([y1, y2, y3, y4])
average = datasets.mean(axis=0)
std_dev = datasets.std(axis=0)
plt.errorbar(x, average, yerr=std_dev)
plt.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
