【问题标题】:Printing value in each bin in hist2d (matplotlib)在 hist2d (matplotlib) 中的每个 bin 中打印值
【发布时间】:2017-04-21 09:13:33
【问题描述】:

我想创建一个二维直方图,在每个 bin 中,该 bin 表示的值显示在给定 bin 的中心。例如,大小为 5x5 的 hist2d 在最终图中将有 25 个值。这对 PyROOT 来说是可行的,但我需要在这里使用 matplotlib/pyplot。

已根据第一个答案尝试了以下方法:

fig, ax = plt.subplots()
ax.set_aspect("equal")
hist, xbins, ybins, im = ax.hist2d(x, y, bins=(4, [1,2,3,5,10,20]))
ax.text(xbins[1]+0.5,ybins[1]+0.5, "HA", color="w", ha="center", va="center", fontweight="bold")

img = StringIO.StringIO()
plt.savefig(img, format='svg')
img.seek(0)
print("%html <div style='width:500px'>" + img.getvalue() + "</div>")

没有任何错误消息,但“HA”根本不会显示在第一个 bin 中。我在 Zeppelin 中对此进行编程,因此我需要从缓冲区中获取 img ...

【问题讨论】:

  • 你能用seaborn吗?
  • 通过以这种方式定义的箱,我实现了箱的非恒定间隔。这工作得很好。这意味着例如y 方向的第三个 bin 取范围 3-5。
  • seaborn 可以胜任,除了非常量的分箱。

标签: python matplotlib histogram


【解决方案1】:

要注释 hist2d 绘图,就像任何其他绘图一样,您可以使用 matplotlib 的 text 方法。要注释的值由返回的直方图给出。注释的位置由直方图边缘(加上一半的 bin 宽度)给出。然后,您可以遍历所有 bin 并在每个 bin 中放置一个文本。

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.poisson(size=(160))
y = np.random.poisson(size=(160))

fig, ax = plt.subplots()
ax.set_aspect("equal")
hist, xbins, ybins, im = ax.hist2d(x,y, bins=range(6))

for i in range(len(ybins)-1):
    for j in range(len(xbins)-1):
        ax.text(xbins[j]+0.5,ybins[i]+0.5, hist.T[i,j], 
                color="w", ha="center", va="center", fontweight="bold")

plt.show()

如果只需要一个注释,例如以下

ax.text(xbins[1]+0.5,ybins[1]+0.5, "HA", 
        color="w", ha="center", va="center", fontweight="bold")

会产生

【讨论】:

  • 我更新了答案以包括打印单个标签。
  • 我认为循环中的 hist 数组的索引是倒置的。很难注意到,因为矩阵中的值差别不大,但 32 单元格的颜色应该较浅,而 25 单元格的颜色应该较暗。
猜你喜欢
  • 2011-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 2017-05-03
  • 1970-01-01
相关资源
最近更新 更多