0
$\begingroup$

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()

`enter image description here

$\endgroup$
  • $\begingroup$ You are plotting a line that connects all points. if you want a might want to use plt.scatter() $\endgroup$ – n1k31t4 Oct 12 '18 at 7:28
2
$\begingroup$

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:

pdf

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: pdf2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.