使用NumPy计算nums针对bins的直方图
在Python中,创建直方图可以使用numpy、matplotlib和seaborn库。在NumPy中,我们有名为histogram()的函数来处理直方图数据。histogram()函数的输入参数是nums和bins。nums用于创建数值数据。
在继续示例之前,让我们首先了解什么是直方图。
什么是直方图
直方图是数据集分布的图形表示。它以一系列条形图的形式表示数据,其中每个条形图代表数据值的范围,条形图的高度代表在该范围内定义的数据值的频率。
它们主要用于表示数值数据的分布,例如班级成绩、人口分布或员工收入分布等。
使用Python中的NumPy计算直方图
在直方图中,x轴表示数据值的范围,分为若干区间;y轴表示每个区间内数据值的频率。通过将每个区间的频率除以总数据值,可以对直方图进行归一化处理,得到相对频率直方图,其中y轴表示每个区间的数值。
语法
以下是为给定数据范围和nums创建直方图的语法。
numpy.histogram(nums, bins, range, normed, weights, density)
其中:
nums是输入数值数据。
bins是图表中表示数据的条形图数量。
range定义直方图中的值范围。
normed支持density参数。
weights是可选参数,为每个数据值加权。
Density参数用于将直方图数据归一化以形成概率密度。
示例
在下面的示例中,我们通过定义nums和直方图中需要的bins数量来创建学生的成绩。histogram()函数通过将nums和bins作为输入参数来生成直方图。
import numpy as np
import matplotlib.pyplot as plt
nums = np.random.normal(50,20,size = 50)
hist = np.histogram(nums)
print("The histogram of the given data:",hist)
plt.hist(hist)
plt.show()
输出
以下是使用nums针对bins的histogram()函数的输出。
The histogram of the given data: (array([ 1, 0, 0, 6, 7, 9, 8, 12, 4, 3]), array([-11.52097959, -1.64606252, 8.22885455, 18.10377162,
27.97868869, 37.85360576, 47.72852282, 57.60343989,
67.47835696, 77.35327403, 87.2281911 ]))
示例
让我们看另一个示例来了解使用nums针对bins的histogram()的工作原理。
import numpy as np
import matplotlib.pyplot as plt
nums = np.random.normal(200,20,size = 100)
hist = np.histogram(nums)
print("The histogram of the given data:",hist)
plt.hist(hist)
plt.show()
输出
以下是使用nums针对bins的histogram()函数的输出。
The histogram of the given data: (array([ 2, 1, 8, 17, 18, 24, 13, 11, 3, 3]), array([146.40363927, 156.62124167, 166.83884407, 177.05644647,
187.27404887, 197.49165127, 207.70925367, 217.92685607,
228.14445847, 238.36206086, 248.57966326]))
示例
让我们看另一个示例来使用numpy库的histogram()函数处理nums针对bins的数据。
import numpy as np
import matplotlib.pyplot as plt
nums = np.random.normal(400,30,size = 30)
hist = np.histogram(nums)
print("The histogram of the given data:",hist)
plt.hist(hist)
plt.show()
输出
以下是使用nums针对bins的histogram()函数的输出。
The histogram of the given data: (array([2, 1, 3, 5, 5, 4, 6, 0, 2, 2]), array([340.28832063, 352.48676341, 364.68520618, 376.88364896,
389.08209174, 401.28053451, 413.47897729, 425.67742007,
437.87586284, 450.07430562, 462.2727484 ]))
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP