matplotlib 直方图中的非均匀轴

Non-uniform axis in matplotlib histogram

我想使用 Matplotlib 绘制具有非均匀 x 轴的直方图。 例如,考虑以下直方图:

import matplotlib.pyplot as plt
values = [0.68, 0.28, 0.31, 0.5, 0.25, 0.5, 0.002, 0.13, 0.002, 0.2, 0.3, 0.45,
      0.56, 0.53, 0.001, 0.44, 0.008, 0.26, 0., 0.37, 0.03, 0.002, 0.19, 0.18,
      0.04, 0.31, 0.006, 0.6, 0.19, 0.3, 0., 0.46, 0.2, 0.004, 0.06, 0.]
plt.hist(values)
plt.show()

第一个 bin 密度很高,所以我想放大那里。

理想情况下,我想将 x 轴中的值更改为 [0, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1] 之类的值,使图表中的 bin 宽度保持不变(当然不是数字)。有没有一种简单的方法可以实现这一目标? 欢迎任何意见或建议。

使用垃圾箱可以解决问题。箱子是您为其分配值的值,例如 0.28 将分配给箱子 0.3。下面的代码为您提供了一个使用 bin 的示例:

import matplotlib.pyplot as plt
values = [0.68, 0.28, 0.31, 0.5, 0.25, 0.5, 0.002, 0.13, 0.002, 0.2, 0.3, 0.45,
  0.56, 0.53, 0.001, 0.44, 0.008, 0.26, 0., 0.37, 0.03, 0.002, 0.19, 0.18,
  0.04, 0.31, 0.006, 0.6, 0.19, 0.3, 0., 0.46, 0.2, 0.004, 0.06, 0.]
plt.hist(values, bins=[0, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1])
plt.show()

为了以更合适的方式绘制它,将 x 轴转换为对数刻度会很方便:

plt.hist(values, bins=[0, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1], log=True)

更改 y 轴上的对数刻度。在您的代码中添加以下行将为您的直方图创建一个对数 x 轴:

plt.xscale('log') 

A​​ndré 的解决方案很好,但 bin 宽度不是恒定的。使用 log2 x 轴适合我正在寻找的东西。我使用 np.logspace 使图表中的 bin 宽度保持不变。

这就是我最后做的事情:

import matplotlib.pyplot as plt
values = [0.68, 0.28, 0.31, 0.5, 0.25, 0.5, 0.002, 0.13, 0.002, 0.2, 0.3, 0.45,
        0.56, 0.53, 0.001, 0.44, 0.008, 0.26, 0., 0.37, 0.03, 0.002, 0.19, 0.18,
        0.04, 0.31, 0.006, 0.6, 0.19, 0.3, 0., 0.46, 0.2, 0.004, 0.06, 0.]
bins = np.logspace(-10, 1, 20, base=2)
bins[0]=0
fig, ax = plt.subplots()
plt.hist(values, bins=bins)
ax.set_xscale('log', basex=2)
ax.set_xlim(2**-10, 1)
plt.show()