Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách vẽ histogram từ collections.Counter trong Matplotlib


Vẽ histogram tần suất từ collections.Counter bằng plt.bar() với keys và values của Counter.

  • Tạo list dữ liệu.
  • Tạo Counter d = collections.Counter(data).
  • Vẽ cột: plt.bar(d.keys(), d.values()).

Ví dụ minh họa

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()

Kết quả đầu ra

Cách vẽ histogram từ collections.Counter trong Matplotlib