Matplotlib | 理解直方图中bins表示的数据含义

  • 引出问题
  1. hist作图中 bins 发生变换 y轴的数据也变化 想不通 不是说y轴计算的是频率吗 频率既然是定值 为什么y轴的数据就还会变化?
  2. 那我确定了bins的数值 我想获得bins内各个柱子(bin)中数据点的数量如何获得

bins的变化

先看一组数据

data['Class'].value_counts()
Class
0    284315
1       492
Name: count, dtype: int64
  • 画直方图

f, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(16,4)) # 共享x轴
bins = 30

ax1.hist(data["Amount"][data["Class"]== 1], bins = bins)

ax1.set_title('Fraud')

ax2.hist(data["Amount"][data["Class"] == 0], bins = bins)
ax2.set_title('Normal')

plt.xlabel('Amount ($)')
plt.ylabel('Number of Transactions')
plt.yscale('log')
plt.show()

在这里插入图片描述
查看当bins=30时,各个柱子内数据点的数量

# 计算欺诈交易的直方图
fraud_hist_values, fraud_bin_edges = np.histogram(data["Amount"][data["Class"] == 1], bins=bins)

# 计算正常交易的直方图
normal_hist_values, normal_bin_edges = np.histogram(data["Amount"][data["Class"] == 0], bins=bins)

# 打印每个 bin 中的数据点数量
print("Fraud transactions in each bin:", fraud_hist_values)
print("Normal transactions in each bin:", normal_hist_values)
Fraud transactions in each bin: [316  74  20  16  18   6   7   5   5   2   9   3   0   1   1   1   0   1
   1   3   0   1   0   0   0   1   0   0   0   1]
Normal transactions in each bin: [280387   2917    599    208    110     42     19      8      9      6
      2      2      0      2      0      1      0      0      0      0
      0      0      2      0      0      0      0      0      0      1]

这样看数据的结果 相对难理解 直接放入极端情况 bins=1

Fraud transactions in each bin: [492]
Normal transactions in each bin: [284315]

在这里插入图片描述

matplotlibseabornhist 函数中,Y 轴表示的是每个柱子(bin)中数据点的数量(频数),或者是这些数量的估计概率密度(如果使用了密度标准化)。当您改变 bins 参数时,Y 轴的数据确实会发生变化,原因如下:

  1. 改变 bins 的数量

    • 当您增加或减少 bins 的数量时,您实际上是在改变数据的分组方式。更多的 bins 意味着每个柱子覆盖的值范围更小,这可能导致某些柱子的高度增加或减少,因为数据点被分配到了更多的组中。
  2. 改变 bins 的宽度

    • bins 的宽度直接影响每个柱子的范围。如果 bins 太宽,可能会错过数据的细微变化;如果 bins 太窄,可能会过度强调数据的随机波动。
  3. Y 轴的解释

    • 如果您没有对直方图进行任何标准化,Y 轴显示的是每个 bin 中的计数(频数)。这意味着,如果您有更多的 bins,每个柱子的高度可能会更低,因为数据点被分散到了更多的柱子中。
    • 如果您对直方图进行了密度标准化(例如,通过设置 density=True),Y 轴显示的是估计的概率密度。在这种情况下,直方图的总面积将等于 1,而每个柱子的高度将根据 bins 的宽度进行调整,以保持总面积不变。

示例代码

import matplotlib.pyplot as plt
import numpy as np

# 生成随机数据
data = np.random.randn(1000)

# 不同的 bins 数量
plt.figure(figsize=(12, 6))

# 较少的 bins
plt.subplot(1, 2, 1)
plt.hist(data, bins=10, alpha=0.5, label='10 bins')
plt.legend()

# 较多的 bins
plt.subplot(1, 2, 2)
plt.hist(data, bins=30, alpha=0.5, label='30 bins')
plt.legend()

plt.show()

在这里插入图片描述

在这个例子中,您可以看到,当 bins 的数量从 10 增加到 30 时,每个柱子的高度和宽度都发生了变化。

结论

Y 轴的数据会随着 bins 参数的变化而变化,因为 bins 参数直接影响数据的分组方式和每个柱子的范围。理解这一点对于正确解释直方图和选择适当的 bins 数量非常重要。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胜天半月子

打不打商的无所谓,能帮到你就好

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值