如何在 Matplotlib 中制作两个直方图,使它们具备相同的柱宽?
要制作具有相同柱宽的两个直方图,我们可以计算数据集的直方图。
步骤
创建随机数据 a 和正态分布 b。
初始化变量 bins,使其具有相同的柱宽。
使用 hist() 方法绘制 a 和 bins。
使用 hist() 方法绘制 b 和 bins。
若要显示图形,请使用 show() 方法。
示例
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True a = np.random.random(100) * 0.5 b = 1 - np.random.normal(size=100) * 0.1 bins = 10 bins = np.histogram(np.hstack((a, b)), bins=bins)[1] plt.hist(a, bins, edgecolor='black') plt.hist(b, bins, edgecolor='black') plt.show()
输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP