在 Seaborn 中进行 distplot 时,如何找出使用的 bin 宽度?我有两个数据集我想共享 bin widhts,但不知道如何返回用于第一个数据集的默认值。对于下面的简单示例,我将如何找出使用的 bin 宽度?
import nump as np
import seaborn as sns
f, axs = plt.subplots(1,1)
distribution=np.random.rand(1000)
sns.distplot(distribution, hist=True , kde_kws={"shade": True},ax=axs)
Run Code Online (Sandbox Code Playgroud)
如果函数中未指定参数,则Seaborn 使用Freedman-Diaconis 规则计算bin 宽度binsseaborn.distplot()
等式如下(来自维基百科):
我们可以使用以下代码计算 IQR 和n的立方根。
Q1 = np.quantile(distribution, 0.25)
Q3 = np.quantile(distribution, 0.75)
IQR = Q3 - Q1
cube = np.cbrt(len(distribution)
Run Code Online (Sandbox Code Playgroud)
该箱宽度是:
In[] : 2*IQR/cube
Out[]: 0.10163947994817446
Run Code Online (Sandbox Code Playgroud)
最后,我们现在可以计算bin的数量。
In[] : 1/(2*IQR/cube) # '1' is the range of the array for this example
Out[]: 9.838696543015526
Run Code Online (Sandbox Code Playgroud)
当我们对结果进行四舍五入时,它等于 10。这就是我们的 bin 数量。我们现在可以指定bins参数以获得相同数量的 bin(或相同范围的相同 bin 宽度)
没有指定 bin 的图形:
f, axs = plt.subplots(1,1)
distribution=np.random.rand(1000)
sns.distplot(distribution, hist=True , kde_kws={"shade": True},ax=axs)
Run Code Online (Sandbox Code Playgroud)
带有指定参数的图形bins=10:
f, axs = plt.subplots(1,1)
sns.distplot(distribution, bins=10, hist=True , kde_kws={"shade": True},ax=axs)
Run Code Online (Sandbox Code Playgroud)
更新:
Seaborn 0.9 版提到了Freedman-Diaconis 规则作为计算 bin 大小的一种方式:
hist bin 的规范,或 None 使用 Freedman-Diaconis 规则。
0.10 版本中的描述更改如下:
hist bin 的规范。如果未指定,则使用 as 引用规则尝试找到有用的默认值。
| 归档时间: |
|
| 查看次数: |
2357 次 |
| 最近记录: |