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

วิธีใช้ Subplot สร้าง 2 กราฟใน Figure เดียวด้วย Matplotlib ใน Python

บทนำ

ฟังก์ชัน subplot (pyplot interface) สร้าง Grid ของ Subplots อย่างรวดเร็ว รูปแบบ subplot(nrows, ncols, index)

การติดตั้ง

pip install matplotlib

Dependencies

Python>=3.4, NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil

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

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 6.0)
x2 = np.linspace(0.0, 3.0)
y1 = np.cos(2.3 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2.4 * np.pi * x2)

plt.subplot(2, 1, 1)      # 2 rows, 1 col, 1st plot
plt.plot(x1, y1, 'o-')
plt.title('2 plots using "subplot" function')
plt.ylabel('Plot 1')

plt.subplot(2, 1, 2)      # 2 rows, 1 col, 2nd plot
plt.plot(x2, y2, '.-')
plt.xlabel('x-axis')
plt.ylabel('Plot 2')

plt.show()

คำอธิบาย

  • subplot(2,1,1) และ subplot(2,1,2) แบ่ง Figure 2 แถว 1 คอลัมน์

  • Plot แรก: Damped oscillation (marker 'o-')

  • Plot ที่สอง: Cosine wave (marker '.-')