NumPy 直方图

NumPy 直方图是数值数据分布的图形表示。使用 histogram()plt() 等函数,我们可以创建和绘制直方图。

我们将仔细研究直方图以及如何在 NumPy 中创建和绘制它们。


NumPy 直方图

NumPy 有一个内置函数 histogram(),它将数据数组作为参数。

在直方图中,一个“箱”(bin)是代表一组数据的数值范围。bin 是一个可选参数。

让我们看一个例子。

import numpy as np

# create an array of data
data = np.array([5, 10, 15, 18, 20])

# create bin to set the interval
bin = [0,10,20,30]

# create histogram
graph = np.histogram(data, bin)

print(graph)

输出

(array([1, 3, 1]), array([ 0, 10, 20, 30]))

在此示例中,我们使用了 histogram() 函数来计算数据的频率分布。我们传递了两个参数:databin

histogram() 函数返回一个包含两个数组的元组:

  • 第一个数组包含每个 bin 内数据的频率计数,
  • 第二个数组包含 bin 的边界。

从结果输出中,我们可以看到:

  • data 数组中,只有 **1** 个数据点(即 **5**)落在 **0** 和 **10** 的 bin 边界之间。
  • **3** 个数据点(即 **10、15、18**)落在 **10** 和 **20** 之间,
  • **1** 个数据点(即 **20**)落在 **20** 和 **30** 之间。

示例:NumPy 直方图

import numpy as np

# create an array of data
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3])

# create bin to set the interval
bin = [0, 5, 10]

# create histogram
graph = np.histogram(data, bin)

print(graph)

输出

(array([7, 4]), array([ 0,  5, 10]))

在这里,histogram() 函数返回一个数组元组。分析输出,data 数组中有 **7** 个数据点落在 **0** 和 **5** 的 bin 边界内,有 **4** 个数据点落在 **5** 和 **10** 之间。


绘制直方图

我们可以使用 plt() 函数来绘制直方图返回的数值。

plt() 是 Matplotlib 提供的函数。要使用 plt(),我们需要导入 Matplotlib。

让我们看一个例子。

import numpy as np
from matplotlib import pyplot as plt

# create an array of data
data = np.array([5, 10, 15, 18, 20])

# create bin to set the interval
bins = [0,10,20,30]

# create histogram
graph = np.histogram(data, bins)
print(graph)

# plot histogram 
plt.hist(data, bins)

plt.show()

输出

(array([1, 3, 1]), array([ 0, 10, 20, 30]))
Plotting a Histogram
绘制直方图

在上面的示例中,我们使用了 histogram() 函数来计算数据的频率分布,然后使用 matplotlib 库中的 plt.hist() 函数绘制了生成的直方图。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战