如何在matplotlib 2d直方图中使bin标签居中?[重复]

问题描述 投票:1回答:1

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

产生了这个图2d histogram

正如你所看到的,bin标签没有居中。我怎样才能编辑标签方案,使bin标签([0,15][0,6])是在bin的中心吗?

python numpy matplotlib histogram histogram2d
1个回答
0
投票

如果你的输入值是整数,你可以使用 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()

resulting plot

© www.soinside.com 2019 - 2024. All rights reserved.