Skip to main content
 首页 » 编程设计

python之如何提高 matplotlib 中二维直方图的灵敏度

2025年05月04日7lovecherry

我在 matplotlib 中构建了反射(reflect)单元格权重的直方图。从下面的直方图中可以看出,颜色区分非常模糊,人们几乎看不到。 这可能是因为我选择了权衡点的方式。

如何提高直方图的“敏感度”,使其能够显示高权重区域和低权重区域之间的区别?


编辑

按要求附上代码:

def generateFreqMap(trajectories, pointWeightLists, representatives): 
    # these three lists are all in a one-to-one correpondance 
    xOfAllPoints = [point[0] for trajectory in trajectories for point in trajectory] 
    yOfAllPoints = [point[1] for trajectory in trajectories for point in trajectory] 
    weightsOfAllPoints =[pointWeight for pointWeightList in pointWeightLists for pointWeight in pointWeightList] 
    leftBound, rightBound, topBound, bottomBound = min(xOfAllPoints), max(xOfAllPoints), max(yOfAllPoints), min(yOfAllPoints) 
    # parameters for histogram 
    x_edges = np.linspace(int(mt.floor(leftBound)), int(mt.ceil(rightBound)), int(mt.ceil(rightBound))-int(mt.floor(leftBound))+1) 
    y_edges = np.linspace(int(mt.floor(bottomBound)), int(mt.ceil(topBound)), int(mt.ceil(topBound))-int(mt.floor(bottomBound))+1) 
    # construct the histogram 
    wcounts = np.histogram2d(xOfAllPoints, yOfAllPoints, bins=(x_edges, y_edges), normed=False, weights=weightsOfAllPoints)[0] 
    # wcounts is a 2D array, with each element representing the weighted count in a bins 
    # show histogram 
    extent = x_edges[0], x_edges[-1], y_edges[0], y_edges[-1] 
    imshow(np.transpose(wcounts), extent=extent, alpha=0.5, cmap=cm.summer) # alpha controls the transparency 
    plt.xlabel('x (m)') 
    plt.ylabel('y (m)') 
    plt.title('Histogram of %i Trajectories'%TRAJECTORY_NUMBER); 
    savefig(PROJECT_PATH + '\\data\\%i_histogram.svg'%len(trajectories)) 
    return wcounts 

第i个点的权重是0.995^i。所以第1点的权重最大,为1。

请您参考如下方法:

在 imshow() 中使用 vmin 和 vmax 参数。

这里的问题是动态范围太宽。我敢打赌,如果您在直方图旁边显示颜色条,您会立即明白为什么会发生这种情况。由于我无法复制您的实验,因此我将对此进行一些猜测。

例如,您在所有单元格中的最高权重高达 500。同时,您的最低权重低至零。然后你的直方图将不得不从它的一种颜色极端到反射(reflect) 500 差异的另一种颜色。这就是区别如此之小的原因。

我建议你的是,虽然我不知道你的问题,但我相信当重量超过一定水平时,比如50,它是51还是500都无所谓。所以借助 vmin 和 vmax 参数:

imshow(np.transpose(wcounts), extent=extent, alpha=0.5, cmap=cm.summer, vmin=0, **vmax=50**) # alpha controls the transparency