使用 Matplotlib 繪製直方圖,並設定 Y 軸為百分比
要使用 matplotlib 繪製以百分比作為 Y 軸的直方圖,可以採取以下步驟:
建立一個數字列表作為 y。
建立一定數量的 bins。
使用 hist() 方法繪製直方圖,其中 y、bins 和 edgecolor 作為引數傳遞。儲存補丁以在 Y 軸上設定百分比。
從給定的字母數字中建立顏色列表。
要設定百分比,請迭代補丁(在步驟 3 中獲取)。
設定 Y 軸刻度範圍。
要顯示圖形,請使用 show() 方法。
示例
import random import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True y = [4, 1, 8, 7, 6, 4, 2, 1, 2, 5] nbins = 10 _, _, patches = plt.hist(y, bins=nbins, edgecolor='white') colors = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(nbins)] for patch in patches: patch.set_facecolor(colors[np.random.randint(100) % nbins]) x = patch.get_x() + patch.get_width() / 2 y = patch.get_height() + .05 plt.annotate('{:.1f}%'.format(y), (x, y), ha='center') plt.ylim(0, 3) plt.show()
輸出
廣告