【问题标题】:Non-uniform axis in matplotlib histogrammatplotlib直方图中的非均匀轴
【发布时间】:2018-12-03 20:06:26
【问题描述】:

我想使用 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 宽度不变(但不是数字,当然)。有没有简单的方法来实现这一目标? 欢迎任何cmets或建议。

【问题讨论】:

    标签: python matplotlib histogram bins


    【解决方案1】:

    使用垃圾箱可以解决问题。 bin 是您为其分配值的值,例如 0.28 将分配给 bin 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') 
    

    【讨论】:

    • 谢谢安德烈!这不是我想要的,因为结果图中的 bin 宽度不是恒定的,但你的解决方案启发了我。
    【解决方案2】:

    André 的解决方案很不错,但 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 2019-09-17
      • 2013-08-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多