2012-07-23

Random variables in Python


import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm


# generate 1000 instances of a normal random variable
mean, sigma = 0, 1
sample = norm.rvs(mean, sigma, size=1000)


# a 50-bin histogram of the sample
plt.hist(sample, 50, normed=1, facecolor='white')


# the population distribution
range = np.arange(-5, 5, 0.001)
plt.plot(range, norm.pdf(range, mean, sigma), color='red', linewidth=4)


plt.show()

Result:



Addendum: the code above can be improved

2012-07-22

How to plot a normal distribution in Python


Python code (slightly adapted from StackOverflow) to plot a normal distribution.

# Plot a normal distribution


import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm


mean = 0
standard_deviation = 1


# Plot between -10 and 10 with .001 steps.
range = np.arange(-10, 10, 0.001)


# Mean = 0, SD = 1.
plt.plot(range, norm.pdf(range, mean, standard_deviation))


plt.show()

Result:



Addendum: the code above can be 
improved