ขั้นตอนการทำงาน
- กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
- สร้าง figure และชุด subplots ด้วย subplots()
- สร้างข้อมูล x ด้วย numpy
- พล็อต x บน axes ax1 ด้วย plot()
- พล็อต x และ 2*x บน ax2 ด้วย plot()
- วางข้อความที่มุมกราฟด้วย annotate() สำหรับ axes ต่างๆ
- ใช้เมธอด show() เพื่อแสดงรูปภาพ
ตัวอย่างโค้ด
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axes = plt.subplots(2)
x = np.linspace(-2, 2, 10)
axes[0].plot(x)
axes[1].plot(x, 2*x)
for ax in axes:
ax.annotate('Straight Line', xy=(1, 0), xycoords='axes fraction', fontsize=10, horizontalalignment='right', verticalalignment='bottom')
plt.show()
ผลลัพธ์
