nbe*_*ker 13 python matplotlib histogram seaborn
我想在seaborn distplot中有一个权重选项,类似于numpy直方图中的权重选项.如果没有此选项,唯一的替代方法是将权重应用于输入数组,这可能会导致不切实际的大小(和时间).
小智 8
您可以通过使用hist_kws参数将权重传递给底层matplotlib的直方图函数来提供权重,如下所示:
sns.distplot(..., hist_kws={'weights': your weights array}, ...)
Run Code Online (Sandbox Code Playgroud)
但是请注意,权重将仅传递给基础直方图;的kde或fit函数distplot都不会受到影响。
正如@vlasisla 在他们的回答中已经提到的,应该通过关键字参数提供权重,hist_kws以便将它们传递给 mathpolotlib 的hist函数。但是,除非kde同时禁用(核密度估计)选项,否则这不会产生任何影响。这段代码实际上会产生预期的效果:
sns.distplot(x, hist_kws={'weights': x_weights}, kde=False)
Run Code Online (Sandbox Code Playgroud)
要理解为什么权重和 kde 都不允许,让我们考虑以下示例,其中x_weights的计算方式为x_weights = np.ones_like(x) / len(x)所有 bin 的高度总和为 1:
# generate 1000 samples from a normal distribution
np.random.seed(8362)
x = np.random.normal(size=1000)
# calculate weights
x_weights = np.ones_like(x) / len(x)
# figure 1 - use weights
sns.distplot(x, hist_kws={'weights': x_weights}, kde=False)
# figure 2 - default plot with kde
sns.distplot(x)
Run Code Online (Sandbox Code Playgroud)
图 1. 使用带有权重的 dist 而不是 KDE 图 2. 使用带有默认参数的 dist
在图 1 中,我们提供了dist带权重的函数,因此在该图中,所有 bin 的高度总和为 1。在图 2 中,默认行为dist是启用的,因此KDE 函数下的区域总和为 1,并且 bin 的高度相应地标准化。现在很容易看出,在提供权重时绘制 KDE 确实没有多大意义。