在matplotlib pyplot 2d直方图中,我怎样才能使我的bin标签在x和y上居中?
我试过以下方法。
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()
正如你所看到的,bin标签没有居中。我怎样才能编辑标签方案,使bin标签([0,15]
和 [0,6]
)是在bin的中心吗?
如果你的输入值是整数,你可以使用 bins=[np.arange(-0.5, 16, 1), np.arange(-0.5, 7, 1)]
给予17个边界([-0.5, 0.5, ..., 15.5]
),共16个选项((-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()