代码之家  ›  专栏  ›  技术社区  ›  rvinas

Matplotlib柱状图中的非均匀轴

  •  0
  • rvinas  · 技术社区  · 6 年前

    我想用matplotlib绘制一个不均匀x轴的柱状图。 例如,考虑以下柱状图:

    导入matplotlib.pyplot as plt 值=[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(值) 请显示())

    第一个垃圾箱的密度很高,所以我想放大它。

    理想情况下,我希望将X轴中的值更改为类似于[0,0.005,0.01,0.02,0.05,0.1,0.2,0.5,1],keeping the bin widths constant within the graph(but not numerically,of course).有没有一个简单的方法来实现这一点? 欢迎提出任何意见或建议。

    Demo histogram

    第一个箱子的密度很高,所以我想放大。

    理想情况下,我想将X轴上的值更改为 [0, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1] 使纸槽宽度在图表中保持不变(当然不是数字)。有没有一个简单的方法来实现这一点? 欢迎提出任何意见或建议。

    2 回复  |  直到 6 年前
        1
  •  1
  •   rvinas    6 年前

    使用垃圾箱可以解决问题。箱是您分配值的值,例如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()
    

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

    plt.xscale('log') 
    
        2
  •  0
  •   rvinas    6 年前

    Andr的解决方案很好,但料箱宽度不是恒定的。使用log2 x轴适合我正在寻找的。我使用 np.logspace 在图表中使纸槽宽度恒定。

    导入matplotlib.pyplot as plt 0.04,0.31,0.006,0.6,0.19,0.3,0.,0.46,0.2,0.004,0.06,0。] ax.设置xlim(2**-10,1)

    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()
    

    Histogram log2