【问题标题】:How do I find the bin with the highest count using np.hist2D()如何使用 np.hist2D() 找到计数最高的 bin
【发布时间】:2020-02-04 14:56:22
【问题描述】:

有没有办法从np.hist2D() 中找到计数最高的垃圾箱。 到目前为止我的代码是:

counts, xedges, yedges = np.histogram2d(x,y bins=100) # x and y are two lists of numbers
print (len(counts), len(xedges), len(yedges)) # 100 101 101

我设法获得了counts,但很难将其与 x 和 y 边缘联系起来。

谢谢。

更新:

我已经解决了 - 欢迎任何更简洁的解决方案。

【问题讨论】:

    标签: python numpy histogram histogram2d


    【解决方案1】:

    要获得最大值,请使用counts.max()。要获得最大值的索引,请使用argmax,后跟unravel_index,如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()
    

    【讨论】:

      【解决方案2】:

      用途:

      cou =[]
      for x in range (0, 100):
          for y in range (0, 100):
              c = counts[x][y]
              cou.append(c)
      print (max(cou))
      

      【讨论】:

        猜你喜欢
        • 2013-05-02
        • 1970-01-01
        • 1970-01-01
        • 2010-12-05
        • 2021-04-21
        • 2019-08-27
        • 1970-01-01
        • 1970-01-01
        • 2014-12-31
        相关资源
        最近更新 更多