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

วิธีพล็อตกราฟหลายกราฟใน Figure เดียวกันด้วย Matplotlib และ Python

Matplotlib เป็นแพ็กเกจ Python ยอดนิยมที่ใช้สำหรับการแสดงข้อมูล (Data Visualization) การแสดงข้อมูลเป็นขั้นตอนสำคัญ เนื่องจากช่วยให้เข้าใจลักษณะข้อมูลได้โดยไม่ต้องมองตัวเลขหรือคำนวณซับซ้อน และช่วยสื่อสารข้อมูลเชิงปริมาณให้ผู้ชมเข้าใจได้อย่างมีประสิทธิภาพ

ภาพรวมของ Matplotlib

Matplotlib ใช้สร้างกราฟ 2 มิติ พร้อม API แบบเชิงวัตถุ (Object-oriented API) ที่ช่วยฝังกราฟลงในแอปพลิเคชัน Python ได้ รองรับการทำงานกับ IPython shells, Jupyter Notebook, Spyder IDE และอื่นๆ เขียนด้วย Python และสร้างขึ้นจาก NumPy (Numerical Python)

การติดตั้ง

pip install matplotlib

ข้อกำหนดเบื้องต้น (Dependencies)

Python (>= 3.4), NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil

ตัวอย่าง: พล็อตกราฟ 2 กราฟใน Figure เดียวกัน

import numpy as np
import matplotlib.pyplot as plt

x1_val = np.linspace(0.0, 6.0)
x2_val = np.linspace(0.0, 3.0)
y1_val = np.cos(2.3 * np.pi * x1_val) * np.exp(-x1_val)
y2_val = np.cos(2.4 * np.pi * x2_val)

fig, (ax1, ax2) = plt.subplots(2, 1)
fig.suptitle('Two plots')

ax1.plot(x1_val, y1_val, 'o-')
ax1.set_ylabel('Plot 1')

ax2.plot(x2_val, y2_val, '.-')
ax2.set_xlabel('x-axis')
ax2.set_ylabel('Plot 2')

plt.show()

ผลลัพธ์

วิธีพล็อตกราฟหลายกราฟใน Figure เดียวกันด้วย Matplotlib และ Python

คำอธิบาย

  • นำเข้าแพ็กเกจที่จำเป็นและตั้งชื่ออเลียส (alias) เพื่อความสะดวก
  • สร้างข้อมูล 2 ชุดด้วยไลบรารี NumPy
  • สร้าง Figure ว่างด้วยฟังก์ชัน subplots()
  • พล็อตข้อมูลด้วยฟังก์ชัน plot()
  • ตั้งค่า label แกน X, แกน Y และหัวข้อด้วย set_xlabel, set_ylabel, set_title
  • แสดงผลด้วยฟังก์ชัน show()