การพล็อตกราฟพื้นฐานด้วย Matplotlib
Matplotlib เป็น library หลักสำหรับการพล็อตกราฟใน Python
การติดตั้ง
pip install matplotlib
1. พล็อตเส้นตรง (Line Plot)
ขั้นตอน
- import matplotlib.pyplot as plt
- กำหนด x, y coordinates
- plt.plot(x, y)
- ตั้งค่า xlabel, ylabel, title
- plt.show()
ตัวอย่าง
import matplotlib.pyplot as plt
x = [1, 3, 5, 7]
y = [2, 4, 6, 1]
plt.plot(x, y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple line graph")
plt.show()
2. พล็อต Bar Chart (แผนภูมิแท่ง)
ขั้นตอน
- กำหนด left_coordinates (ตำแหน่งแท่ง)
- กำหนด heights (ความสูง)
- กำหนด labels
- plt.bar(left, heights, tick_label=labels, width=0.6, color=['red', 'black'])
- ตั้งค่า labels, title, show()
ตัวอย่าง
import matplotlib.pyplot as plt
left = [1, 2, 3, 4, 5]
heights = [10, 20, 30, 15, 40]
labels = ['One', 'Two', 'Three', 'Four', 'Five']
plt.bar(left, heights, tick_label=labels, width=0.6, color=['red', 'black'])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title("A simple bar graph")
plt.show()
กราฟอื่นๆ ที่นิยม
- Histogram: plt.hist(data)
- Pie Chart: plt.pie(sizes, labels=labels)
- Scatter: plt.scatter(x, y)
- Subplots: fig, axes = plt.subplots(nrows, ncols)
Best Practices
- ใช้ OO interface:
fig, ax = plt.subplots()แล้วax.plot() - ใช้
plt.tight_layout()ป้องกัน overlap - บันทึกรูป:
plt.savefig('plot.png', dpi=300)