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

การเติมข้อมูลลงใน Subplots ผ่าน Loop และ Function ใน Matplotlib


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

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้าง figure และชุด subplots แถว 3 คอลัมน์ 2
  • สร้างฟังก์ชันวนลูปคอลัมน์ของแต่ละแถวและพล็อตข้อมูล x ด้วย plot() ที่แต่ละดัชนีคอลัมน์
  • วนลูปแถว สร้างข้อมูล x แบบสุ่ม และเรียกฟังก์ชัน iterate_columns()
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

import numpy as np
import matplotlib.pyplot as plt

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

fig, axes = plt.subplots(3, 2)

def iterate_columns(cols, x):
    for col in cols:
        col.plot(x, color='red')

for row in axes:
    x = np.random.normal(0, 1, 100).cumsum()
    iterate_columns(row, x)

plt.show()

ผลลัพธ์

การเติมข้อมูลลงใน Subplots ผ่าน Loop และ Function ใน Matplotlib