Matplotlib เป็นแพ็กเกจ Python ยอดนิยมสำหรับ Data Visualization ช่วยเข้าใจข้อมูลโดยไม่ต้องมองตัวเลขหรือคำนวณซับซ้อน และสื่อสารข้อมูลเชิงปริมาณได้อย่างมีประสิทธิภาพ สร้างกราฟ 2 มิติ ด้วย Object-oriented API รองรับ IPython, Jupyter, Spyder ฯลฯ เขียนด้วย Python บน NumPy
การติดตั้งและ Dependencies
pip install matplotlib
Python (>= 3.4), NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil
ตัวอย่าง: สร้าง Histogram พร้อมเส้นโค้ง Bell Curve
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19875871)
meanVal = 125
stdDevVal = 35
x = meanVal + stdDevVal * np.random.randn(764)
num_bins = 36
fig, ax = plt.subplots()
n, bins, patches = ax.hist(x, num_bins, density=True)
y = ((1 / (np.sqrt(2 * np.pi) * stdDevVal)) *
np.exp(-0.5 * (1 / stdDevVal * (bins - meanVal))**2))
ax.plot(bins, y, '--')
ax.set_xlabel('X-axis')
ax.set_ylabel('y-axis')
ax.set_title('A simple histogram')
fig.tight_layout()
plt.show()
ผลลัพธ์

คำอธิบาย
- นำเข้าแพ็กเกจและตั้งอเลียส
- สร้างข้อมูลด้วย
random.seed - กำหนดค่า Mean และ Standard Deviation
- กำหนดจำนวน Bins (แท่งสี่เหลี่ยมใน Histogram)
- สร้าง Figure ว่างด้วย
subplots() - สร้าง Histogram ด้วยฟังก์ชัน
hist() - พล็อตข้อมูลด้วย
plot() - ตั้งค่า Label แกน X, Y และ Title
- แสดงการกระจายแบบ Bell Curve ด้วยเส้นจุด
- แสดงผลด้วย
show()