如何在 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()
輸出
廣告