python - Seaborn 直方图 bin 宽度未扩展到 bin 标签

标签 python matplotlib histogram seaborn

这个问题与我上一个问题不同。 我正在通过以下代码使用 facetgrid 打印直方图。

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt

titanic = sns.load_dataset("titanic")
g= sns.FacetGrid(titanic, col ='survived', size = 3, aspect = 2)
g.map(plt.hist, 'age', color = 'r'), plt.show()
plt.show()

我让 seaborn 决定 bins 标签/值,这就是我想出的

enter image description here

我注意到条形图本身并没有一直延伸到标签。 因此 0-10 标签中的第一个条形似乎一直延伸到 8 岁左右,而不是完全延伸到 10 岁。快速计算 value_count(除非我弄错了)表明第一个条形确实只包括 8 岁之前的事件.

然后我尝试通过以下代码更改要包含的垃圾箱数量:

g.map(plt.hist, 'age', bins =8, color = 'r'), plt.show()

但是左边的图表看起来还是不对。 enter image description here

最佳答案

因此,您在轴上看到的标签与 bin 的宽度关系不大。实际上,选择轴上的标签使得数据在相应的轴上可见。如果让 seaborn(实际上是 matplotlib)选择 bin 大小和数量,也会发生类似的事情。如果您指定 bin 编号,则选择 bin 的宽度,以使整个 x 范围的数据位于 bin 内。

如果你想控制 bin 的宽度,你需要为 bin 参数传递一个列表,而不仅仅是一个数字。假设您想要从 0 到 100 的 10 个分箱,您可以这样写:

g.map(plt.hist, 'age', bins=range(0, 110, 10)], color = 'r')

这会给你:

enter image description here

因此,bins 看起来像 [0, 10, ..., 100]

您可能不希望被如此硬编码,并希望有一些更灵活的方式来指定 bin。一种选择是定义 bin 宽度,并从数据的开始到结束都有 bin。这可能看起来像这样:

b_width = 10  # chose an arbitrary value here
my_bins = np.arange(min(titanic['age']), max(titanic['age']) + b_width, b_width)
g.map(plt.hist, 'age', bins=my_bins, color = 'r')

注意:np.arange 是我们使用 float 时需要的。如果您的数据仅为整数,您也可以为此使用 range

现在您可能还想调整 xticks 以便它们也显示 bin 开始。 Pyplot 对此有方便的命令:

plt.xticks(range(0, 110, 10))

或者对于后一个例子:

plt.xticks(np.around(my_bins, decimals=1))

可能需要 np.around,因为您的数据可能从 float 开始,这在 x 轴刻度标签上看起来很难看。 还要注意 plt.xticks 可以做更多方便的事情,所以你应该去 have a loock .

希望对您有所帮助!

关于python - Seaborn 直方图 bin 宽度未扩展到 bin 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40473646/

相关文章:

python - 极坐标直方图 - 没有错误,但没有意义

python - 删除各个子目录中相同的文件名

python - 如何将选定的行移动到 pandas 中的下一个相邻列?

python - 以不同名称循环保存图像

python - 如何使用 matplotlib 渲染 latex 矩阵

python - 如何在水平条形图中绘制计数器对象?

r - 在 R 中绘制矩阵 "by parts"?

r - 使用 R 处理日期时格式化直方图 x 轴

python - 在 jinja2 的列表中的每个字符串周围添加引号?

python - 不同步长的欧拉方法。如何更改算法代码以适应不同的步长值?