ฮิสโตแกรมแบบขั้ว (Polar Histogram) หรือ Rose Diagram ใช้แสดงการกระจายของข้อมูลมุม (angular data) เช่น ทิศทางลม เวลาที่เกิดเหตุการณ์ หรือทิศทางการเคลื่อนที่ ใช้ projection='polar' ใน subplot
ขั้นตอนการทำงาน
- นำเข้า
numpyและmatplotlib.pyplot - สร้างข้อมูลมุม
theta(0 ถึง 2π), รัศมีradii, และความกว้างwidth - สร้าง Polar subplot ด้วย
plt.subplot(111, projection='polar') - พลอตแท่งด้วย
ax.bar(theta, radii, width=width, bottom=0.0) - วนลูปปรับสีและความโปร่งใสของแต่ละแท่งตามค่า radii
- แสดงผลด้วย
plt.show()
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
N = 20
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
ax = plt.subplot(111, projection='polar')
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.rainbow(r / 10.0))
bar.set_alpha(0.5)
plt.show()
คำอธิบายพารามิเตอร์สำคัญ
| พารามิเตอร์ | คำอธิบาย |
|---|---|
projection='polar' | สร้าง Axes แบบ Polar coordinates |
theta | มุม (เรเดียน) ตำแหน่งแท่ง |
radii | ความยาวรัศมี (ความสูงแท่ง) |
width | ความกว้างมุมของแต่ละแท่ง (เรเดียน) |
bottom | รัศมีเริ่มต้น (ค่าเริ่มต้น 0) |
การปรับแต่งเพิ่มเติม
# ตั้งค่าทิศทาง 0 องศา (North/Up) และทิศทางเข็มนาฬิกา
ax.set_theta_zero_location('N') # 'N', 'E', 'S', 'W'
ax.set_theta_direction(-1) # -1 = clockwise, 1 = counterclockwise
# ตั้งค่า grid และ ticks
ax.set_thetagrids(np.arange(0, 360, 45), labels=['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'])
ax.set_rgrids([2, 4, 6, 8, 10])
# เพิ่ม colorbar
import matplotlib.cm as cm
norm = cm.colors.Normalize(vmin=0, vmax=10)
sm = cm.ScalarMappable(cmap='rainbow', norm=norm)
sm.set_array([])
plt.colorbar(sm, ax=ax, pad=0.1, label='Magnitude')
การประยุกต์ใช้
เหมาะสำหรับ: Rose diagram (ทิศทางลม) การวิเคราะห์ทิศทางการแตกของแร่ธาตุ Chronobiology (รูปแบบเวลา) Radar cross-section หรือข้อมูลมุมทุกประเภท