如何在 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()

输出

更新日期: 2021 年 5 月 11 日

2K+ 次浏览

启动你的 职业生涯

完成课程认证

开始学习
广告
© . All rights reserved.