gpt4 book ai didi

python - 将 matplotlib 直方图除以最大 bin 值

转载 作者:太空宇宙 更新时间:2023-11-03 11:50:05 24 4
gpt4 key购买 nike

我想在同一个图上绘制多个直方图,我需要比较数据的分布。我想通过将每个直方图除以它的最大值来做到这一点,这样所有的分布都具有相同的比例。然而,matplotlib 的直方图函数的工作方式,我还没有找到一个简单的方法来做到这一点。

这是因为n在

n, bins, patches = ax1.hist(y, bins = 20, histtype = 'step', color = 'k')

是每个 bin 中的计数,但我无法将其重新传递给 hist,因为它会重新计算。

我已尝试使用范数和密度函数,但它们对分布的面积进行了归一化,而不是对分布的高度进行了归一化。我可以复制 n,然后使用 bins 输出重复 bin 边缘,但这很乏味。当然 hist 函数必须允许 bins 值除以一个常数?

示例代码如下,演示了问题。

y1 = np.random.randn(100)
y2 = 2*np.random.randn(50)
x1 = np.linspace(1,101,100)
x2 = np.linspace(1,51,50)
gs = plt.GridSpec(1,2, wspace = 0, width_ratios = [3,1])
ax = plt.subplot(gs[0])
ax1 = plt.subplot(gs[1])
ax1.yaxis.set_ticklabels([]) # remove the major ticks

ax.scatter(x1, y1, marker='+',color = 'k')#, c=SNR, cmap=plt.cm.Greys)
ax.scatter(x2, y2, marker='o',color = 'k')#, c=SNR, cmap=plt.cm.Greys)
n1, bins1, patches1 = ax1.hist(y1, bins = 20, histtype = 'step', color = 'k',linewidth = 2, orientation = 'horizontal')
n2, bins2, patched2 = ax1.hist(y2, bins = 20, histtype = 'step', linestyle = 'dashed', color = 'k', orientation = 'horizontal')

Example output. I want the max bins of the dashed and dotted lines to be 1.

最佳答案

我不知道 matplotlib 是否默认允许这种规范化,但我自己编写了一个函数来完成它。

它从 plt.hist(如上)获取 nbins 的输出,然后将其传递给下面的函数。

def hist_norm_height(n,bins,const):
''' Function to normalise bin height by a constant.
Needs n and bins from np.histogram or ax.hist.'''

n = np.repeat(n,2)
n = float32(n) / const
new_bins = [bins[0]]
new_bins.extend(np.repeat(bins[1:],2))
return n,new_bins[:-1]

现在要绘制(我喜欢阶梯直方图),将其传递给 plt.step。

例如plt.step(new_bins,n)。这将为您提供一个高度由常数归一化的直方图。

关于python - 将 matplotlib 直方图除以最大 bin 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29981799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com