简体   繁体   中英

Passing distribution parameters to seaborn histogram plot

I'm trying to plot a distribution along a lognorm distribution to see how good the fit is. How can I pass the distribution parameters to the fit function?

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sampled = np.random.lognormal(0.5, 0.25, 1000)

sns.distplot(sampled, fit=stats.lognorm)
plt.show()

This works, but I can't pass the distribution parameters:

shape, location, scale = stats.lognorm.fit(sampled)

sns.distplot(sampled, fit=stats.lognorm, fit_kws={"shape" : shape, 'location':location,'scale':scale})

I get this error message:

AttributeError: 'Line2D' object has no property 'shape'

fit_kws contains the parameters for the curve (linestyle, color, ...) of the fitted curve. You can't provide your own parameters for fitting.

If the standard fit isn't good enough, you can just draw your own fitted distribution on top of the distplot :

import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import numpy as np

sampled = np.random.lognormal(0.5, 0.25, 1000)
ax = sns.distplot(sampled, kde_kws={'label': 'kde'}, label='histogram')

shape, location, scale = stats.lognorm.fit(sampled)
x_min, x_max = ax.get_xlim()
xs = np.linspace(x_min, x_max, 200)
ax.plot(xs, stats.lognorm.pdf(xs, s=shape, loc=location, scale=scale), color='r', ls=':', label='fitted lognormal')
ax.set_xlim(x_min, x_max) # set the limits back to the ones of the distplot
plt.legend()
plt.show()

结果图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM