如何在 Matplotlib 中從直方圖資料繪製折線圖?
要在 matplotlib 中從直方圖資料繪製折線圖,我們使用 numpy 直方圖方法來計算一組資料的直方圖。
步驟
向當前數字新增一個子圖,nrows=2, ncols=1 和 index=1。
使用 numpy 直方圖方法獲取一組資料的直方圖。
使用直方圖hist() 方法與邊框顏色=黑色繪製直方圖。
在索引 2 處,使用計算出的資料(來自 numpy 直方圖)。要繪製它們,我們可以使用 plot() 方法。
要顯示數字,請使用show() 方法。
範例
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True plt.subplot(211) data = np.array(np.random.rand(100)) y, binEdges = np.histogram(data, bins=100) plt.hist(data, bins=100, edgecolor='black') plt.subplot(212) bincenters = 0.5 * (binEdges[1:] + binEdges[:-1]) plt.plot(bincenters, y, '-', c='black') plt.show()
輸出
廣告