如何使用 Matplotlib 繪製 collections.Counter 直方圖?


若要使用 collections.Counter 繪製直方圖,我們可以使用 bar() 方法。在 bar() 方法中,我們可以使用 collections.counter() 來獲得每個元素的頻率。將元素及其頻率作為高度。

步驟

  • 設定圖片大小並調整子圖之間的填充。
  • 生成一個數據點列表。
  • 使用 collections.Counter() 獲取字典 d
  • 使用 d.keys()d.values() 生成柱狀圖。
  • 若要顯示圖片,請使用 show() 方法。

示例

import collections
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = [0, 1, 2, 4, 1, 3, 0, 4, 1, 4, 3, 5, 6, 5, 2]

d = collections.Counter(data)

plt.bar(d.keys(), d.values())

plt.show()

輸出

更新日期:2021 年 6 月 18 日

3K+ 瀏覽量

開啟您的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.