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

วิธีพล็อตกราฟใน Python ด้วย Matplotlib

การพล็อตกราฟพื้นฐานด้วย Matplotlib

Matplotlib เป็น library หลักสำหรับการพล็อตกราฟใน Python

การติดตั้ง

pip install matplotlib

1. พล็อตเส้นตรง (Line Plot)

ขั้นตอน

  1. import matplotlib.pyplot as plt
  2. กำหนด x, y coordinates
  3. plt.plot(x, y)
  4. ตั้งค่า xlabel, ylabel, title
  5. 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 (แผนภูมิแท่ง)

ขั้นตอน

  1. กำหนด left_coordinates (ตำแหน่งแท่ง)
  2. กำหนด heights (ความสูง)
  3. กำหนด labels
  4. plt.bar(left, heights, tick_label=labels, width=0.6, color=['red', 'black'])
  5. ตั้งค่า 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)