📜  在Python中使用 NumPy 计算一组数据的直方图

📅  最后修改于: 2022-05-13 01:54:41.268000             🧑  作者: Mango

在Python中使用 NumPy 计算一组数据的直方图

Numpy 为我们提供了使用NumPy.histogram()函数计算给定数据集的直方图的功能。直方图的形成取决于数据集,无论是预定义的还是随机生成的。

案例一:借助随机数据集计算 Numpy 直方图

Python3
# import Numpy and matplotlib
from matplotlib import pyplot as plt
import numpy as np
  
  
# Creating random dataset
data_set = np.random.randint(100, size=(50))
  
# Creation of plot
fig = plt.figure(figsize=(10, 6))
  
# plotting the Histogram with certain intervals
plt.hist(data_set, bins=[0, 10, 20, 30, 40, 50,
                         60, 70, 80, 90, 100])
  
# Giving title to Histogram
plt.title("Random Histogram")
  
# Displaying Histogram
plt.show()


Python3
# import Numpy and matplotlib
from matplotlib import pyplot as plt
import numpy as np
  
  
# Using predefined dataset
data_set = [45, 85, 95, 10, 58, 77, 92, 72, 52,
            22, 32, 5, 95, 2, 23, 24, 50, 40, 60,
            69, 44, 80, 21, 15, 17, 55, 21, 88]
  
# Creation of plot
fig = plt.figure(figsize=(10, 5))
  
# plotting the Histogram with certain intervals
plt.hist(data_set, bins=[0, 15, 30, 45, 60, 75, 90, 105])
  
# Giving title to Histogram
plt.title("Predefined Histogram")
  
# Displaying Histogram
plt.show()


输出:

在上面的示例中,我们使用np.random.randint()创建了一个随机数据集并绘制了 Numpy 直方图

案例2:借助预定义数据集计算Numpy直方图

Python3

# import Numpy and matplotlib
from matplotlib import pyplot as plt
import numpy as np
  
  
# Using predefined dataset
data_set = [45, 85, 95, 10, 58, 77, 92, 72, 52,
            22, 32, 5, 95, 2, 23, 24, 50, 40, 60,
            69, 44, 80, 21, 15, 17, 55, 21, 88]
  
# Creation of plot
fig = plt.figure(figsize=(10, 5))
  
# plotting the Histogram with certain intervals
plt.hist(data_set, bins=[0, 15, 30, 45, 60, 75, 90, 105])
  
# Giving title to Histogram
plt.title("Predefined Histogram")
  
# Displaying Histogram
plt.show()

在上面的示例中,我们采用预定义的数据集并绘制 Numpy 直方图。