# Gaussian distribution in python without using libraries

I am implementing Gaussian distribution of a variable, but it gives multiple bell shapes. It should be a single bell shape. Below is my code and plot.

def gaussian_transform(arr):

u=arr.mean()

sig=arr.std()

fd=[]

a=0
pi=math.pi
for i in arr:

a=((i-u)**2)/(2*(sig**2))
e=math.exp(-a)
fd.append((1/(sig*math.sqrt(2*pi))) * e)

return fd

y=gaussian_transform(df.Age)

plt.plot(df.Age,y)

plt.ylabel('some numbers')
plt.show()




You need to sort arr. For example you sort df.Age then apply the function and after plotting you will get a beautiful chart.

For example, I used your function and a range from 0 to 99 that is already sorted:

import numpy as np
import math
from matplotlib import pyplot as plt

arr = np.arange(100)
y=gaussian_transform(arr)
plt.plot(arr,y)


and got the following plot:

To make the plot smooth you need to add more points to the chart. In the following code I used vector functions of numpy to make the computation faster and write less code. I also used the linspace function to fill in the space between max and min of the data with more points for smooth charts.

import numpy as np
import math
from matplotlib import pyplot as plt

def gaussian_plot(arr , n=1000):
u = arr.mean()
sig = arr.std()
x = np.linspace(arr.min(), arr.max(), n)
e = np.exp(-a)
y = 1/(sig*math.sqrt(2*math.pi)) * e
return x, y

arr = np.arange(100)
x, y=gaussian_plot(arr, 10000)
plt.plot(x,y)
`

And the result:

• thanks it works.but its not smooth curve. – Athar Noraiz Oct 13 '18 at 8:46
• I changed the answer to make a smooth curve – keiv.fly Oct 13 '18 at 12:17
• If you are satisfied with the answer please mark it as answered. – keiv.fly Oct 13 '18 at 13:01