0

I am very new to coding, and I am trying to create a bell curve Gaussian that creates bars with the bin width 10 and quantity 30. Here us the code I am currently using.

import numpy as np 
from matplotlib import pyplot as plt
from scipy.stats import norm 
domain = np.linspace(-2,2,1000)
bins = np.linspace(0, 10, 30)
plt.plot(domain, norm.pdf(domain,0,1), bins)
plt.show()

However when I plot them, I get two lines. I now see that it is because I am using np.linspace but how can I create the bins?

1 Answers1

1

If you are new to coding you best start with using you defined functions instead of imported modules so you know what you are doing

Let's start by defining the Gaussian PDF function:

import numpy as np
def gauss(x, mu, sigma, scale):
    return scale*np.exp(-(x-mu)**2/(2*sigma**2))

Then define your domain:

x = np.arange(start,end,step)

Where start and end are the start and the end of your domain and step is your "binsize". Otherwise you can use:

x = np.linspace(start,end,nbins)

Which is self explanatory.

Then you can calculate the pdf values using the defined function and plot them

import matplotlib.pyplot as plt
y = gauss(x,0,1,1)
y2 = gauss(x,0,5,1)
fig,ax = plt.subplots()
ax.plot(x,y,'r',label='Normal PDF')
ax.plot(x,y2,'k',label='Sigma is 5')
plt.legend()
plt.show()
Edo98
  • 433
  • 2
  • 9
  • How an I able to set the width of the bins = to say 5? – Karla Silva 107 Jun 03 '20 at 18:58
  • The bin size is controlled by the array you feed to the function, you can use x = np.arange(-10,10,5). Mind that theese are not real bins, you are just evaluating a gaussian pdf at various points. If you want to generate data and make an histogram you should use np.hist – Edo98 Jun 03 '20 at 21:46