在Python中使用NumPy计算一组数据的柱状图
Numpy为我们提供了使用NumPy.histogram()函数计算给定数据集的直方图的功能。直方图的形成取决于数据集,无论它是预定义的还是随机生成的。
语法 : numpy.histogram(data, bins=10, range=None, normed=None, weights=None, density=None)
案例1:在随机数据集的帮助下计算Numpy直方图
# 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()
输出:
在上面的例子中,我们使用np.random.randint()创建了一个随机数据集,并绘制了Numpy Histogram
案例2:借助预设的数据集计算Numpy柱状图
# 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直方图。