【问题标题】:weights option for seaborn distplot?seaborn distplot 的权重选项?
【发布时间】:2015-10-20 14:14:28
【问题描述】:

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

【问题讨论】:

  • 或者更好,一个numpy直方图输入参数

标签: python matplotlib histogram seaborn


【解决方案1】:

您可以通过使用 hist_kws 参数将权重传递给底层 matplotlib 的直方图函数来提供权重,如下所示:

sns.distplot(..., hist_kws={'weights': your weights array}, ...)

但请注意,权重只会传递给底层直方图; kde 和distplot 的拟合功能都不会受到影响。

【讨论】:

    【解决方案2】:

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

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

    要了解为什么不允许使用 weights 和 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)
    

    Figure 1. Using dist with weights and not KDE Figure 2. Using dist with default parameters

    在图 1 中,我们提供了带有权重的 dist 函数,因此在该图中所有 bin 的高度总和为 1。在图 2 中,dist 的默认行为已启用,因此KDE 函数下的面积总和为 1,并且相应地对 bin 的高度进行了归一化。现在很容易看出,在提供权重的情况下绘制 KDE 确实没有多大意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-05
      • 2019-04-19
      • 2019-08-03
      • 2021-11-26
      • 2017-12-29
      • 1970-01-01
      • 2017-10-12
      • 1970-01-01
      相关资源
      最近更新 更多