要获得最大值,请使用counts.max()
. 要获得最大值的索引,请使用argmax
后跟unravel_index
as in np.unravel_index(np.argmax(counts), counts.shape)
。索引可用于查找 bin 的 x 和 y 边缘。
这是一个示例,以及显示所有内容如何组合在一起并检查结果的可视化。请注意,bins=100
生成 10000 个 bin;在示例中,每个方向仅使用 10 个 bin 以获得清晰的绘图。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
N = 200
x = np.random.uniform(0, 80, N)
y = np.random.uniform(0, 40, N)
counts, xedges, yedges = np.histogram2d(x, y, bins=(10, 10))
x_ind, y_ind = np.unravel_index(np.argmax(counts), counts.shape)
print(f'The maximum count is {counts[x_ind][y_ind]:.0f} at index ({x_ind}, {y_ind})')
print(f'Between x values {xedges[x_ind]} and {xedges[x_ind+1]}')
print(f'and between y values {yedges[y_ind]} and {yedges[y_ind+1]}')
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.scatter(x,y,marker='.',s=20,lw=0)
rect = Rectangle((xedges[x_ind], yedges[y_ind]), xedges[x_ind+1] - xedges[x_ind], yedges[y_ind+1] - yedges[y_ind],
linewidth=1,edgecolor='crimson',facecolor='none')
ax1.add_patch(rect)
ax1.set_title(f'max count: {counts[x_ind][y_ind]:.0f}')
ax2.imshow(counts.T, origin='lower')
ax2.plot(x_ind, y_ind, 'or')
ax2.set_title('heatmap')
plt.show()