บทนำ
Matplotlib รองรับการสร้าง Subplots หลายแผนภูมิใน Figure เดียว ใช้ add_subplot หรือ add_axes สำหรับตำแหน่งกำหนดเอง
การติดตั้ง
pip install matplotlib
Dependencies
Python>=3.4, NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
fig.subplots_adjust(top=0.8)
# Subplot บน (2 rows, 1 col, index 1)
ax1 = fig.add_subplot(211)
ax1.set_ylabel('Y-axis')
ax1.set_title('A simple plot')
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*np.pi*t)
ax1.plot(t, s, color='blue', lw=2)
# Subplot ล่าง แบบ Manual Position
np.random.seed(4567232)
ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3]) # [left, bottom, width, height]
n, bins, patches = ax2.hist(np.random.randn(1000), 50, facecolor='yellow', edgecolor='green')
ax2.set_xlabel('x-label')
plt.show()คำอธิบาย
add_subplot(211): Grid 2x1 ตำแหน่งที่ 1add_axes([l,b,w,h]): ระบุตำแหน่ง/size ในหน่วย Normalized (0-1)Subplot แรก: Line plot Sine wave
Subplot ที่สอง: Histogram ข้อมูลสุ่ม