首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在hist2d中打印每个bin中的值(matplotlib)

在hist2d中打印每个bin中的值(matplotlib)
EN

Stack Overflow用户
提问于 2017-04-21 17:13:34
回答 1查看 4.8K关注 0票数 6

我想创建一个二维直方图,在每个柱状图中,由该柱状图表示的值显示在该给定柱状图的中心。例如,大小为5x5的hist2d在最终图形中将有25个值。使用PyROOT可以很好地做到这一点,但在这里我需要使用matplotlib/pyplot。

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

代码语言:javascript
运行
复制
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中编程,因此我需要从buffer中获取img ...

EN

回答 1

Stack Overflow用户

发布于 2017-04-21 18:16:43

要像其他绘图一样注释hist2d绘图,可以使用matplotlib的text方法。要注释的值由返回的直方图给出。注释的位置由直方图边缘(加上二分之一的柱状图宽度)给出。然后,您可以循环遍历所有存储箱,并在每个存储箱中放置一个文本。

代码语言:javascript
运行
复制
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()

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

代码语言:javascript
运行
复制
ax.text(xbins[1]+0.5,ybins[1]+0.5, "HA", 
        color="w", ha="center", va="center", fontweight="bold")

将产生

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43538581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档