Fitting a Normal distribution to 1D data

Adel picture Adel · Nov 15, 2013 · Viewed 115.4k times · Source

I have a 1 dimensional array. I can compute the "mean" and "standard deviation" of this sample and plot the "Normal distribution" but I have a problem:

I want to plot the data and Normal distribution in the same figure.

I dont know how to plot both the data and the normal distribution.

Any Idea about "Gaussian probability density function in scipy.stats"?

s = np.std(array)
m = np.mean(array)
plt.plot(norm.pdf(array,m,s))

Answer

Warren Weckesser picture Warren Weckesser · Nov 16, 2013

You can use matplotlib to plot the histogram and the PDF (as in the link in @MrE's answer). For fitting and for computing the PDF, you can use scipy.stats.norm, as follows.

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


# Generate some data for this demonstration.
data = norm.rvs(10.0, 2.5, size=500)

# Fit a normal distribution to the data:
mu, std = norm.fit(data)

# Plot the histogram.
plt.hist(data, bins=25, density=True, alpha=0.6, color='g')

# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 100)
p = norm.pdf(x, mu, std)
plt.plot(x, p, 'k', linewidth=2)
title = "Fit results: mu = %.2f,  std = %.2f" % (mu, std)
plt.title(title)

plt.show()

Here's the plot generated by the script:

Plot