获取用于海底图的箱宽

时间:2019-08-12 09:36:39

标签: python seaborn

在Seaborn中进行distplot绘制时,如何确定使用了什么箱宽度?我有两个要共享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)

1 个答案:

答案 0 :(得分:1)

如果未在函数seaborn.distplot()

中指定bins参数,Seaborn将使用 Freedman-Diaconis规则计算箱宽

等式如下(来自wikipedia):

Freedman-Diaconis rule

我们可以使用以下代码计算IQR和 n 的立方根。

Q1 = np.quantile(distribution, 0.25)
Q3 = np.quantile(distribution, 0.75)
IQR = Q3 - Q1

cube = np.cbrt(len(distribution)

箱宽为:

In[] : 2*IQR/cube 
Out[]: 0.10163947994817446

最后,我们现在可以计算箱的数量

In[] : 1/(2*IQR/cube) # '1' is the range of the array for this example
Out[]: 9.838696543015526

当我们将结果取整时,总计为10。这是我们的箱数。现在,我们可以指定bins参数来获取相同数量的容器(或相同范围的容器宽度)

不指定垃圾箱的图形:

f, axs = plt.subplots(1,1)
distribution=np.random.rand(1000)
sns.distplot(distribution, hist=True , kde_kws={"shade": True},ax=axs)

Bin width for seaborn distplot

带有参数bins=10的图形:

f, axs = plt.subplots(1,1)
sns.distplot(distribution, bins=10, hist=True , kde_kws={"shade": True},ax=axs)

Bin width