【问题标题】:How to center bin labels in matplotlib 2d histogram? [duplicate]如何在 matplotlib 2d 直方图中居中 bin 标签? [复制]
【发布时间】:2020-06-17 17:46:25
【问题描述】:

对于 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 的中心?

【问题讨论】:

  • 您的轴标签当前是数据值,而不是 bin 标签。 (如果您在随机生成的数据中更改lowhigh,这将更加明显。)通常,了解数据如何以其自然单位分布更有用,而不是它在哪个 bin 中。你确定 bin数字是你想要的?
  • 这能回答你的问题吗? How to center labels in histogram plot
  • 在我的示例中,每个 bin 应该是 1 宽的整数值乘以 1 高的整数值。数据是值介于 0 和 6(总共 7 个选项)和介于 0 和 15(总共 16 个选项)之间的数组。我想要的标签是 x 和 y 轴上的值(0、1、...、6 和 0、1、...、15)。

标签: python numpy matplotlib histogram histogram2d


【解决方案1】:

如果您的输入值是整数,您可以使用 bins=[np.arange(-0.5, 16, 1), np.arange(-0.5, 7, 1)] 为 16 个选项 ((-0.5,0.5), (0.5,1.5), ..., (14.5,15.5)) 提供 17 个边界 ([-0.5, 0.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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-03
    • 2021-07-22
    • 2014-06-08
    • 2016-02-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多