1

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?

Zephyr
  • 11,891
  • 53
  • 45
  • 80
Adam G.
  • 75
  • 11
  • Your axis labels are currently data values, not bin labels. (This will be more obvious if you change `low` or `high` in your randomly generated data.) Usually it's more useful to know how your data is distributed in its natural units, rather than which bin it's in. Are you sure bin numbers are what you want? – Emerson Harkin Jun 17 '20 at 18:00
  • 3
    Does this answer your question? [How to center labels in histogram plot](https://stackoverflow.com/questions/23246125/how-to-center-labels-in-histogram-plot) – Dorian Jun 17 '20 at 18:02
  • In my example, each bin should be an integer value of 1 wide by an integer value of 1 tall. The data are arrays with values that fall between 0 and 6 (7 total options) and between 0 and 15 (16 total options). What I want for labels are those values on the x and y axes (0, 1, ..., 6 and 0, 1, ..., 15). – Adam G. Jun 17 '20 at 19:14

1 Answers1

1

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

JohanC
  • 71,591
  • 8
  • 33
  • 66