我想创建一个二维直方图,在每个柱状图中,由该柱状图表示的值显示在该给定柱状图的中心。例如,大小为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中编程,因此我需要从buffer中获取img ...
发布于 2017-04-21 18:16:43
要像其他绘图一样注释hist2d
绘图,可以使用matplotlib的text
方法。要注释的值由返回的直方图给出。注释的位置由直方图边缘(加上二分之一的柱状图宽度)给出。然后,您可以循环遍历所有存储箱,并在每个存储箱中放置一个文本。
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")
将产生
https://stackoverflow.com/questions/43538581
复制相似问题