แผนย่อย Matplotlib
แสดงหลายแปลง
ด้วยsubplots()
ฟังก์ชันนี้ คุณสามารถวาดหลายแปลงในรูปเดียว:
ตัวอย่าง
วาด 2 แปลง:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
ผลลัพธ์:
แผนย่อย() ฟังก์ชั่น
ฟังก์ชันsubplots()
รับอาร์กิวเมนต์สามตัวที่อธิบายเลย์เอาต์ของรูป
เลย์เอาต์ถูกจัดระเบียบเป็นแถวและคอลัมน์ ซึ่งแสดงโดยอาร์กิวเมนต์แรก และ ตัว ที่สอง
อาร์กิวเมนต์ที่สามแสดงถึงดัชนีของพล็อตปัจจุบัน
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
ดังนั้น หากเราต้องการตัวเลขที่มี 2 แถว 1 คอลัมน์ (หมายความว่าทั้งสองแปลงจะแสดงที่ด้านบนของกันและกันแทนที่จะอยู่เคียงข้างกัน) เราสามารถเขียนรูปแบบดังนี้:
ตัวอย่าง
วาด 2 แปลงทับกัน:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
ผลลัพธ์:
คุณสามารถวาดแผนภาพได้มากเท่าที่ต้องการบนรูปภาพเดียว เพียงแค่อธิบายจำนวนแถว คอลัมน์ และดัชนีของโครงเรื่อง
ตัวอย่าง
วาด 6 แปลง:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,
1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 1)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(2, 3, 2)
plt.plot(x,y)
x = np.array([0, 1,
2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 3, 3)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 3, 4)
plt.plot(x,y)
x = np.array([0, 1, 2, 3])
y =
np.array([3, 8, 1, 10])
plt.subplot(2, 3, 5)
plt.plot(x,y)
x
= np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2,
3, 6)
plt.plot(x,y)
plt.show()
ผลลัพธ์:
ชื่อ
คุณสามารถเพิ่มชื่อเรื่องในแต่ละพล็อตด้วยtitle()
ฟังก์ชัน:
ตัวอย่าง
2 แปลงพร้อมชื่อเรื่อง:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
plt.show()
ผลลัพธ์:
ซูเปอร์ไตเติ้ล
คุณสามารถเพิ่มชื่อเรื่องให้กับทั้งร่างด้วยsuptitle()
ฟังก์ชัน:
ตัวอย่าง
เพิ่มชื่อเรื่องสำหรับทั้งร่าง:
import matplotlib.pyplot as plt
import numpy as np
#plot 1:
x =
np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30,
40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
plt.suptitle("MY SHOP")
plt.show()
ผลลัพธ์: