如何使用 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()
輸出

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP