Matplotlib Subplots
Hiển thị nhiều lô
Với subplots()
chức năng này, bạn có thể vẽ nhiều ô trong một hình:
Thí dụ
Vẽ 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()
Kết quả:
Hàm con ()
Hàm subplots()
nhận ba đối số mô tả bố cục của hình.
Bố cục được sắp xếp theo hàng và cột, được biểu thị bằng đối số thứ nhất và thứ hai .
Đối số thứ ba đại diện cho chỉ số của âm mưu hiện tại.
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.
Vì vậy, nếu chúng ta muốn một hình có 2 hàng và 1 cột (nghĩa là hai ô sẽ được hiển thị chồng lên nhau thay vì cạnh nhau), chúng ta có thể viết cú pháp như sau:
Thí dụ
Vẽ 2 ô chồng lên nhau:
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()
Kết quả:
Bạn có thể vẽ bao nhiêu ô bạn muốn trên một hình, chỉ cần xác định số hàng, cột và chỉ số của ô.
Thí dụ
Vẽ 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()
Kết quả:
Chức vụ
Bạn có thể thêm tiêu đề cho mỗi âm mưu bằng title()
chức năng:
Thí dụ
2 mảnh đất, với tiêu đề:
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()
Kết quả:
Siêu tiêu đề
Bạn có thể thêm tiêu đề cho toàn bộ hình bằng suptitle()
chức năng:
Thí dụ
Thêm tiêu đề cho toàn bộ hình:
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()
Kết quả: