如何找出在 Seaborn 中进行 distplot 时使用的 bin 宽度?我有两个数据集,我想共享 bin 宽度,但不知道如何返回用于第一个数据集的默认值。对于下面的简单示例,我如何找出使用的 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)
最佳答案
如果函数中未指定 bins
参数,Seaborn 将使用 Freedman-Diaconis 规则来计算 bin 宽度 seaborn.distplot()
等式如下(来自wikipedia):
我们可以使用以下代码计算 IQR 和 n 的立方根。
Q1 = np.quantile(distribution, 0.25)
Q3 = np.quantile(distribution, 0.75)
IQR = Q3 - Q1
cube = np.cbrt(len(distribution)
bin 宽度为:
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。这就是我们的 bin 数量。我们现在可以指定 bins
参数来获取相同数量的 bin(或相同范围的相同 bin 宽度)
不指定容器的图表:
f, axs = plt.subplots(1,1)
distribution=np.random.rand(1000)
sns.distplot(distribution, hist=True , kde_kws={"shade": True},ax=axs)
指定参数bins=10
的图表:
f, axs = plt.subplots(1,1)
sns.distplot(distribution, bins=10, hist=True , kde_kws={"shade": True},ax=axs)
更新:
Seaborn 0.9 版提到Freedman-Diaconis 规则作为计算 bin 大小的方法:
Specification of hist bins, or None to use Freedman-Diaconis rule.
0.10版本中的描述更改如下:
Specification of hist bins. If unspecified, as reference rule is used that tries to find a useful default.
关于python - 获取用于seaborn图的bin宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57458789/