打印hist2d中每个仓位的值(matplotlib)

2024-05-17 10:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个二维柱状图,在每一个箱子里,这个箱子代表的数值显示在那个箱子的中心。例如,一个大小为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”。我正在用齐柏林飞艇编程,所以我需要从缓冲区取img。。。在


Tags: divimgplt代表ax中心数值center
1条回答
网友
1楼 · 发布于 2024-05-17 10:18:55

要注释hist2d图,就像任何其他绘图一样,可以使用matplotlib的text方法。要注释的值由返回的直方图给出。注释的位置由柱状图边缘(加上一半的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[i,j], 
                color="w", ha="center", va="center", fontweight="bold")

plt.show()

enter image description here

如果只需要一个注释,例如:

^{2}$

会产生

enter image description here

相关问题 更多 >