Normal distribution

Let's see how we can fit and plot a normal distribution to a data set. First we'll import the necessary modules, then we create a dummy data set. With numpy we can create a normal distributed data with an unknown mean. Here we generate a random mean between 30 and 50 and a standard deviation a tenth of the mean.

In [1]:
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt

# Create a dummy data set
dummy_mean = np.random.randint(30, 50)
dummy_std = dummy_mean*0.1
x = np.random.normal(loc=dummy_mean, scale=dummy_std, size=100)

Fit a normal distribution to the data

With matplotlib we can plot a histogram of the data with ax.hist() to get a feel for what the data set contains.

Apparently I had to to the fit in the same code block or the plot wouldn't show, I guess that's just how it it sometimes. So in the second part here we calculate mean and standard deviation for the data. Then we create a range for the x-axis for which we calculate the probability density function for based on the mean and standard deviation. Lastly we plot that and touch up the figure a bit.

In [2]:
# Create a plot object and plot the dummy data
fig, ax = plt.subplots()
ax.hist(x, alpha=0.3, density=True, bins=15)

# Fit normal distribution of the dummy data
mu, std = norm.fit(x)
xmin, xmax = plt.xlim(mu-4*std, mu+4*std)
x_range = np.linspace(xmin, xmax, 1000)
y_pdf = norm.pdf(x_range, mu, std)
ax.plot(x_range, y_pdf, linewidth=1.5, color='black')

# Plot aestethics
title = f'Normal distribution fit: $\\mu$={round(mu, 2)}, $\\sigma$={round(std, 2)}'
plt.title(title)
plt.ylabel('Probability Density Function (PDF)')
plt.xlabel('Value')
Out[2]:
Text(0.5, 0, 'Value')
No description has been provided for this image