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

n, bins, patches ใน Matplotlib Histogram คืออะไร

Method plt.hist() คืนค่า 3 ตัว: n (จำนวนในแต่ละ Bin), bins (ขอบเขต Bin), patches (Rectangle Artists)

คำอธิบายแต่ละค่า

ตัวแปรประเภทคำอธิบาย
nArrayจำนวน Observations ในแต่ละ Bin (ความสูงแท่ง)
binsArrayขอบเขตของแต่ละ Bin (length = n_bins + 1)
patchesList[Rectangle]List ของ Rectangle Artists (แท่ง Bar) สำหรับปรับสี/สไตล์

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


import numpy as np
import matplotlib.pyplot as plt

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

x = np.random.normal(size=100)

# รับค่าทั้ง 3 ตัว
n, bins, patches = plt.hist(x, bins=100)

# ปรับสีแท่งแรก (Index 0)
plt.setp(patches[0], 'facecolor', 'yellow')

# ใช้ n และ bins สำหรับคำนวณเพิ่มเติม
print(f"Total count: {n.sum()}")
print(f"Bin edges: {bins[:5]}...")  # แสดง 5 ค่าแรก
print(f"Number of patches: {len(patches)}")

plt.show()

การใช้ Patches ปรับแต่งแท่งแต่ละอัน


# สีสลับกัน
for i, patch in enumerate(patches):
    patch.set_facecolor('red' if i % 2 == 0 else 'blue')

# Gradient ตามความสูง
max_n = max(n)
for patch, height in zip(patches, n):
    patch.set_facecolor(plt.cm.viridis(height / max_n))

ผลลัพธ์

Histogram 100 Bins แท่งแรก (ซ้ายสุด) สีเหลือง ส่วนอื่นสี Default