首页 > 解决方案 > 在python中对三个数据集的直方图进行归一化

问题描述

plt.subplots(figsize=(12,9))
n, bins, patches = plt.hist(x, 50, normed=1, histtype='step', lw=2, color='blue', 
                   label='color _22')
n, bins, patches = plt.hist(y, 50, normed=1, histtype='step', lw=2, color='red', 
                   label='color _20')
n, bins, patches = plt.hist(z, 50, normed=1, histtype='step', lw=2, color='green', 
                   label='color _18')
plt.legend(loc='upper left')

我想规范化这三个数据集。当我使用上述脚本进行绘图时,我得到了一个非标准化绘图。请让我知道我该怎么做才能正常化。

在此处输入图像描述

标签: pythonmatplotlibplothistogram

解决方案


您正在使用normed=1,这是现在称为 的旧参数density=True。在最新版本中,normed导致错误消息;在之前的版本中,它会生成一个弃用警告。

无论如何,使用normed=1(或density=True)你已经得到了一个归一化的直方图。注意这里的归一化意味着:总面积等于一。这与箱宽度有关:箱宽度乘以所有箱高度之和等于一。

您会注意到蓝色直方图更宽,而绿色直方图的峰值吸收了宽度的差异。因此,两者都具有与红色直方图有效相同的面积 (1)。

或者,您可以建议另一种类型的标准化,其中直方图高度定义为最高条的百分比。下面的代码显示了它的样子。为了避免需要绘制两次直方图,np.histogram用于计算 bin 值,可以通过plt.step.

from matplotlib import pyplot as plt
from matplotlib.ticker import PercentFormatter
import numpy as np

N = 1000
x = np.concatenate([np.random.normal(0, 0.04, N), np.random.uniform(-3, 3, 10)])
y = np.concatenate([np.random.normal(0, 0.06, N), np.random.uniform(-3, 3, 10)])
z = np.concatenate([np.random.normal(0, 0.08, N), np.random.uniform(-3, 3, 10)])
for data, color, label in zip((x, y, z), ('b', 'r', 'g'), ('x', 'y', 'z')):
    hist, bins = np.histogram(data, 50)
    plt.step(bins, np.pad(hist, (1, 0)) / hist.max(), where='pre', lw=2, color=color, alpha=0.8, label=label)
plt.ylim(0, None)
plt.gca().yaxis.set_major_formatter(PercentFormatter(1))
plt.legend()
plt.show()

示例图

请注意,默认情况下,直方图 bin 采用将其划分为相等部分的范围x.min()x.max()示例中为 50)。由于 3 个数据数组没有相同的minmax,所以边界有些随意。您可以通过为or提供显式range=(-2, 2)来设置所有这些边界相等。如果您只对中心部分感兴趣,则可以将该范围设置得更窄。plt.histnp.histogram


推荐阅读