I have manually fitted a lognormal distribution to my data:
from scipy.stats import lognorm
sigma = 0.15
mu = 2
x_fit = np.linspace(x.min(), x.max(), 100)
y_fit = lognorm.pdf(x_fit, sigma, scale=np.exp(mu))
fig, ax = plt.subplots()
plt.plot(x_fit, y_fit, color='red')
Problem is that scipy does not converge to sigma = 0.15, but it only converges to mu ~ 2. Plus, I am getting some inf as well... Note: This is occurring even if I use [2, 0.15] as starting guess:
from scipy.optimize import curve_fit
y, x = np.histogram(z_data, bins=100)
x = (x[1:]+x[:-1])/2 # bin centers
def fit_lognormal(x, mu, sigma):
return lognorm.pdf(x, sigma, scale=np.exp(mu))
p0 = [2, 0.15]
params = curve_fit(fit_lognormal, x, y, p0=p0)
params
This returns:
(array([1.97713319e+00, 6.98238900e-05]),
array([[inf, inf],
[inf, inf]]))

You forgot to scale your histogram to have an unitary area using the switch
density:Lets say you dataset is the following:
You can fit the parameters in three easy ways:
Natively with
stats:Where
loc ~ 0andscale ~ np.exp(2).Using
curve_fitto fit the PDF:Using MLE and
minimize: