pythonnumpymatplotlibhistogramhistogram2d

How to center bin labels in matplotlib 2d histogram?


How can I center my bin labels in x and y for a matplotlib pyplot 2d histogram?

I've tried the following:

import numpy as np
import matplotlib.pyplot as plt

ns = np.random.uniform(low=0,high=6,size=200)
dets = np.random.uniform(low=0,high=15,size=200)
plt.figure()
h = plt.hist2d(dets,ns,bins=(16,7))
plt.colorbar(h[3])
plt.xticks(np.arange(0,16,1))
plt.yticks(np.arange(0,7,1))

plt.show()

which produces this plot: 2d histogram

and as you can see, the bin labels are not centered. How can I edit the labeling scheme so that the bin labels ([0,15] and [0,6]) are at the center of the bins?


Solution

  • If your input values are integers, you can use bins=[np.arange(-0.5, 16, 1), np.arange(-0.5, 7, 1)] giving 17 boundaries ([-0.5, 0.5, ..., 15.5]) for 16 total options ((-0.5,0.5), (0.5,1.5), ..., (14.5,15.5)).

    import numpy as np
    import matplotlib.pyplot as plt
    
    # ns = np.random.randint(low=0, high=7, size=200)
    # dets = np.random.randint(low=0, high=16, size=200)
    ns = np.random.uniform(low=0, high=6, size=200)
    dets = np.random.uniform(low=0, high=15, size=200)
    plt.figure()
    hist, xedges, yedges, mesh = plt.hist2d(dets, ns, bins=[np.arange(-0.5, 16, 1), np.arange(-0.5, 7, 1)])
    
    plt.colorbar(mesh)
    plt.xticks(np.arange(0, 16, 1))
    plt.yticks(np.arange(0, 7, 1))
    plt.show()
    

    resulting plot