NumPy - 使用 Matplotlib 绘制直方图
NumPy - 使用 Matplotlib 创建直方图
Section titled “NumPy - 使用 Matplotlib 创建直方图”直方图 (histogram) 是数值数据分布的图形表示。它将数据点分组到指定的范围(称为 ‘bin’ 或 ‘数据分箱’),并绘制落入每个 bin 的数据点的频率 (count),通常以条形图表示。
numpy.histogram()
Section titled “numpy.histogram()”NumPy 提供了 numpy.histogram() 函数来计算直方图数据(频率和 bin 边界),而无需实际绘制。如果你需要原始计数进行进一步分析,这将很有用。
它接受输入数据数组和期望的 bin 作为主要参数。bin 可以指定为一个整数(等宽 bin 的数量)或一个 bin 边界序列。
import numpy as np
# 示例数据a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
# 显式定义 bin 边界bin_edges = [0, 20, 40, 60, 80, 100]
# 计算直方图# 返回计数 (hist) 和 bin 边界 (bins)hist, bins = np.histogram(a, bins=bin_edges)
print("Frequency counts per bin:")print(hist)print("\nBin edges:")print(bins)输出:
Frequency counts per bin:[4 3 5 2 1]
Bin edges:[ 0 20 40 60 80 100]解释:输出 hist [4 3 5 2 1] 表示:4 个值介于 0 和 20 之间(不包含 20),3 个值介于 20 和 40 之间,5 个值介于 40 和 60 之间,2 个值介于 60 和 80 之间,1 个值介于 80 和 100 之间。bins 输出确认了使用的边界。
使用 matplotlib.pyplot.hist() 绘图
Section titled “使用 matplotlib.pyplot.hist() 绘图”np.histogram() 计算数据,而 matplotlib.pyplot.hist()(通常导入为 plt.hist())则计算(如果需要)并直接绘制直方图。
plt.hist() 将数据数组和 bin 信息(类似于 np.histogram)作为输入,并生成可视化图形。
import matplotlib.pyplot as pltimport numpy as np
# 示例数据 (与之前相同)a = np.array([22, 87, 5, 43, 56, 73, 55, 54, 11, 20, 51, 5, 79, 31, 27])
# 定义 bin 边界bin_edges = [0, 20, 40, 60, 80, 100]
# 直接创建直方图绘制plt.hist(a, bins=bin_edges, edgecolor='black') # 添加边缘颜色以提高清晰度
plt.title("Data Distribution Histogram")plt.xlabel("Value Ranges (Bins)")plt.ylabel("Frequency (Count)")plt.xticks(bin_edges) # 设置 x 轴刻度以匹配 bin 边界
plt.show()预期输出描述:
此代码将显示一个包含条形图(直方图)的窗口。x 轴表示值范围(0-20、20-40、…、80-100)。y 轴表示每个范围内数据点的频率(计数)。将有 5 个条形,其高度对应于之前计算的计数(大约为 4、3、5、2、1)。条形图具有黑色边缘,以提高可见性。