Search code examples
pythonmatplotlibhistogrambins

Non-uniform axis in matplotlib histogram


I would like to plot a histogram with a non-uniform x-axis using Matplotlib. For example, consider the following histogram:

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

Demo histogram

The first bin has high density, so I would like to zoom in there.

Ideally, I would like to change the values in the x-axis to something like [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). Is there an easy way to achieve this? Any comments or suggestions are welcome.


Solution

  • The solution from André is nice, but the bin widths are not constant. Working with a log2 x-axis suits what I was looking for. I use np.logspace to make the bin widths constant in the graph.

    That's what I ended up doing:

    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