seaborn distplot的weights选项是什么?

19
我希望在seaborn distplot中有一个权重选项,类似于numpy直方图。如果没有这个选项,唯一的替代方法是将权重应用于输入数组,这可能导致不切实际的大小(和时间)。

甚至更好的是,一个numpy直方图输入参数。 - nbecker
2个回答

14

您可以通过将权重传递给基础的Matplotlib直方图函数,使用hist_kws参数来提供权重,例如:

```python sns.histplot(data=tips, x="total_bill", weights=tip_percentages, bins=bins, kde=True, stat="density", linewidth=0, alpha=0.7, hist_kws={"edgecolor": "k"}) ```
sns.distplot(..., hist_kws={'weights': your weights array}, ...)

请注意,权重只会传递给基础直方图;distplot的密度曲线和拟合函数都不会受到影响。


5

@vlasisla在他们的回答中已经提到,权重应该通过关键字参数hist_kws提供,以便它们会传递给mathpolotlib的hist函数。不过, 如果同时禁用了kde(核密度估计)选项,则这将不产生任何效果。以下代码实际上会产生所需的效果:

sns.distplot(x, hist_kws={'weights': x_weights}, kde=False)

为了理解为什么不能同时使用权重和KDE,让我们考虑以下示例,其中x_weights的计算方式为x_weights = np.ones_like(x) / len(x),以便所有条形图的高度之和为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)

图1. 使用带权重而非KDE的dist函数 图2. 使用默认参数的dist函数

在图1中,我们使用了带权重的dist函数,因此在该图中所有直方图柱子的高度加起来等于1。在图2中,启用了dist函数的默认行为,因此KDE函数下面的面积等于1,且各个直方图柱子的高度被相应地归一化。现在很容易看出,当提供权重时绘制KDE确实没有多大意义。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接