Skip to main content
 首页 » 编程设计

python之在 matplotlib 中调整/拉伸(stretch) 2d 直方图的大小与 x-y 相关的箱数

2025年05月04日15freeliver54

我正在制作一个二维直方图,如下所示:

import matplotlib as plt 
import numpy as np 
 
hist,xedges,yedges = np.histogram2d(x,y,bins=[50,150],range=[[0,50],[0,150]]) 
Hmasked = np.ma.masked_where(hist==0,hist) # Mask pixels with a value of zero 
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1] ] 
plt.imshow(Hmasked.T,extent=extent,interpolation='nearest',origin='lower') 
plt.show() 

这在 x 方向有 50 个 bin,在 y 方向有 150 个 bin。生成的图在 x 方向上较窄,在 y 方向上较高。如何拉伸(stretch) x 中的图,使 x 中的箱子看起来更宽?如果有代码可以自动将其拉伸(stretch)到正常的图形纵横比,那将是最佳的。

请您参考如下方法:

plt.imshow(Hmasked.T,extent=extent,interpolation='nearest',origin='lower', aspect='auto')