เมื่อใช้วิธี subplot(row, col, index) เราสามารถแบ่งตัวเลขออกเป็นส่วนๆ ของ row*col และสามารถพล็อตภาพที่ตำแหน่งดัชนีได้ ในโปรแกรมต่อไปนี้ เราจะสร้างไดอะแกรมสองไดอะแกรมในรูปเดียว
ขั้นตอน
-
การสร้างจุด x, y1, y2 โดยใช้ numpy
-
ด้วย nrows =1, ncols =2, index =1, เพิ่มแผนย่อยให้กับตัวเลขปัจจุบัน โดยใช้เมธอด subplot()
-
พล็อตเส้นโดยใช้จุด x และ y1 โดยใช้วิธี plot()
-
ตั้งค่าหัวเรื่อง ป้ายกำกับสำหรับแกน X และ Y สำหรับรูปที่ 1 โดยใช้เมธอด plt.title(), plt.xlabel() และ plt.ylabel()
-
ด้วย nrows =1, ncols =2, index =2, เพิ่มแผนย่อยให้กับตัวเลขปัจจุบัน โดยใช้เมธอด subplot()
-
พล็อตเส้นโดยใช้จุด x และ y2 โดยใช้วิธี plot()
-
ตั้งค่าหัวเรื่อง ป้ายกำกับสำหรับแกน X และ Y สำหรับรูปที่ 2 โดยใช้เมธอด plt.title(), plt.xlabel() และ plt.ylabel()
-
หากต้องการแสดงรูป ให้ใช้เมธอด plt.show()
ตัวอย่าง
from matplotlib import pyplot as plt
import numpy as np
xPoints = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
y1Points = np.array([12, 14, 16, 18, 10, 12, 14, 16, 18, 120])
y2Points = np.array([12, 7, 6, 5, 4, 3, 2, 2, 1, 12])
plt.subplot(1, 2, 1) # row 1, col 2 index 1
plt.plot(xPoints, y1Points)
plt.title("My first plot!")
plt.xlabel('X-axis ')
plt.ylabel('Y-axis ')
plt.subplot(1, 2, 2) # index 2
plt.plot(xPoints, y2Points)
plt.title("My second plot!")
plt.xlabel('X-axis ')
plt.ylabel('Y-axis ')
plt.show() ผลลัพธ์
