turaran32
turaran32

Reputation: 93

PDF of a Lognormal Distribution

I have tried to draw a distribution function with a given mean and standard deviation. However, drawing the distribution function only shows the histograms and not the distribution function and I do not know why it is not drawn:

mean = 15.14
stdev = 0.3738
phi = (stdev ** 2 + mean ** 2) ** 0.5
mu = np.log(mean ** 2 / phi)
sigma = (np.log(phi ** 2 / mean ** 2)) ** 0.5
data=np.random.lognormal(mu, sigma , 1000)
mu, sigma, n= lognorm.fit(data) 
plt.hist(data, bins=30, density=True, alpha=0.5, color='b')
# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 1000)
p = lognorm.pdf(x, mu, sigma)
plt.plot(x, p, 'k', linewidth=2)
title = "LogNormal Distribution: Media: {:.2f} y Dev.Est: {:.2f}".format(mean, stdev)
plt.title(title)
plt.show()

The result that I have obtained:

enter image description here

Upvotes: 2

Views: 3955

Answers (1)

Zephyr
Zephyr

Reputation: 12496

Pay attention to the line:

mu, sigma, n = lognorm.fit(data)

there you are overwriting mu and sigma values used later.
lognorm.pdf(x, mu, sigma) returns zeros because you are evaluating the PDF far away from the mean, where the PDF is actually zero.
In order to properly center the PDF on the mean value, you should replace this line of your code:

p = lognorm.pdf(x, mu, sigma)

with:

p = lognorm.pdf(x = x, scale = mean, s = sigma)

Complete Code

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

mean = 15.14
stdev = 0.3738
phi = (stdev ** 2 + mean ** 2) ** 0.5
mu = np.log(mean ** 2 / phi)
sigma = (np.log(phi ** 2 / mean ** 2)) ** 0.5
data=np.random.lognormal(mu, sigma , 1000)
# mu, sigma, n= lognorm.fit(data)
plt.hist(data, bins=30, density=True, alpha=0.5, color='b')
# Plot the PDF.
xmin, xmax = plt.xlim()
x = np.linspace(xmin, xmax, 1000)
p = lognorm.pdf(x = x, scale = mean, s = sigma)
plt.plot(x, p, 'k', linewidth=2)
title = "LogNormal Distribution: Media: {:.2f} y Dev.Est: {:.2f}".format(mean, stdev)
plt.title(title)
plt.show()

enter image description here

Upvotes: 2

Related Questions