python - 获取用于seaborn图的bin宽度

标签 python seaborn

如何找出在 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):

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)

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)

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

更新:

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/

相关文章:

javascript - 在 mac 上使用 cython 和 emscripten 将简单的 python 程序编译为 javascript

python - 有效地将 CSV 列解压到单独的列表中

python - 如何在seaborn fiddle 图上添加阴影?

python - Seaborn 不使用 %matplotlib 笔记本显示图例

python - 绘制一天内具有不同时间戳和 datetime.time 格式的时间序列

python - 如何使用 requests 模块将 SOAP 体内的值作为参数传递

python - 打开多个 Excel 文件,打开每个文件的每个工作表,然后保存图像

python - 将一个应用程序的 url 包含到 django 中另一个应用程序的 urls 文件中

pandas - seabornfacetgrid点图问题

python - 设置seaborn散点图中点的大小