Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเลือก Subplot เฉพาะเจาะจงใน Matplotlib ด้วยโปรแกรม


ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่ด้วยเมธอด figure()
  • วนลูปในช่วงจำนวน subplots ที่ต้องการวาง
  • ในลูป ให้เพิ่ม axes เข้าไปใน figure โดยใช้เมธอด add_subplot()
  • เลือก axes ที่ต้องการและพล็อตเส้นสีแดง
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

ตัวอย่างโค้ด

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
for index in [1, 2, 3, 4]:
    ax = fig.add_subplot(1, 4, index)
    ax.plot(np.random.rand(5), np.random.rand(5))
ax = fig.add_subplot(1, 4, 2)
ax.plot(np.random.rand(5), np.random.rand(5), color='red')
plt.show()

ผลลัพธ์

วิธีเลือก Subplot เฉพาะเจาะจงใน Matplotlib ด้วยโปรแกรม