如何在Matplotlib中制作具有相同bin宽度的两个直方图?
要使两个直方图具有相同的bin宽度,我们可以计算数据集的直方图。
步骤
- 创建随机数据a和正态分布b。
-
为相同的bin宽度初始化变量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()