Search code examples
pythonnumpyscipygaussian

Difference between scipy.stats.norm.pdf and plotting gaussian manually


I'm plotting a simple normal distribution using scipy.stats, but for some reason when I try to compare it to the regular gaussian formula the plot looks very different:

import numpy as np
import scipy.stats as stats

x = np.linspace(-50,175,10000)
sig1, mu1  = 10.0, 30.0

y1 = stats.norm.pdf(x, mu1, sig1)
y11 = np.exp(-(x-mu1)**2/2*sig1)/(np.sqrt(2*np.pi*sig1))

plt.plot(x,y11)
plt.plot(x,y1)

The result is:

enter image description here

Can someone explain to me why they are not the same?


Solution

  • stats.norm.pdf requires sigma, but in your calculation you are using it as variance. Also there are two brackets missing.

    import matplotlib.pyplot as plt
    import numpy as np
    import scipy.stats as stats
    
    x = np.linspace(-50, 175, 10000)
    sig1, mu1 = 10.0, 30.0
    var1 = sig1 ** 2
    
    y1 = stats.norm.pdf(x, mu1, sig1)
    y11 = np.exp(-((x - mu1) ** 2) / (2 * var1)) / (np.sqrt(2 * np.pi * var1))
    
    plt.plot(x, y11)
    plt.plot(x, y1)
    plt.show()
    

    Which produces the same plot.

    Cheers!