Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Matplotlib – สร้าง Histogram ความถี่จาก List ที่มี Tuple Elements

ภาพรวม

เมื่อมีข้อมูลเป็น list of tuples (label, value) สามารถแยกเป็น 2 list แล้วพลอต Bar Chart ได้ ซึ่งทำหน้าที่เหมือน Histogram ความถี่

ขั้นตอนการทำงาน

  • กำหนดขนาดฟิกเกอร์
  • สร้าง list of tuples: [("a", 1), ("c", 3), ...]
  • แยก label และ frequency ออกเป็น list แยกกัน
  • ใช้ plt.bar() พลอต
  • แสดงผล

ตัวอย่างโค้ด

import matplotlib.pyplot as plt

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

data = [("a", 1), ("c", 3), ("d", 4), ("b", 2), ("e", 7), ("f", 3), ('g', 2)]

labels = [item[0] for item in data]
freqs = [item[1] for item in data]

plt.bar(labels, freqs)
plt.show()

ผลลัพธ์

Bar chart แสดงความถี่ของแต่ละ label

Matplotlib – สร้าง Histogram ความถี่จาก List ที่มี Tuple Elements Matplotlib – สร้าง Histogram ความถี่จาก List ที่มี Tuple Elements

วิธีทำให้สั้นกว่า

# Unzip ด้วย zip(*)
labels, freqs = zip(*data)
plt.bar(labels, freqs)

# หรือใช้ Counter ถ้าข้อมูลยังไม่ได้รวม
from collections import Counter
raw_data = ['a', 'c', 'd', 'b', 'e', 'f', 'g', 'c', 'f', 'b', 'g']
counts = Counter(raw_data)
plt.bar(counts.keys(), counts.values())