python - 在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')
我想规范化这三个数据集。当我使用上述脚本进行绘图时,我得到了一个非标准化绘图。请让我知道我该怎么做才能正常化。
解决方案
您正在使用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 个数据数组没有相同的min
和max
,所以边界有些随意。您可以通过为or提供显式range=(-2, 2)
来设置所有这些边界相等。如果您只对中心部分感兴趣,则可以将该范围设置得更窄。plt.hist
np.histogram
推荐阅读
- python - 为什么我的 python 脚本用另一个表中的虚拟数据填充 Django 表会导致错误?
- excel - 如何在不使用工程函数的情况下将excel中的十进制转换为二进制
- python - 将存储为字符串的列表的 pandas 列拆分为多行(literal_eval 错误)
- android - 如何使浮动操作按钮变成椭圆形
- c# - WPF C# 和适当的体系结构
- git - 如何识别某个命名分支的分支点
- sql - 在一行中批量插入错误的数据
- azure-service-fabric - Service Fabric 中容器化服务的网络超时
- c# - 无法加载文件或程序集 PDFsharp
- loops - 循环错误:错误:无法分配大小为 1003.7 Mb 的向量