ขั้นตอนการทำงาน
- กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
- สร้างข้อมูล x และ y ด้วย numpy
- ใช้ subplots() สร้าง figure และชุด subplots
- พล็อต x และ y ด้วย plot()
- หาค่าเฉลี่ยของอาร์เรย์ x
- พล็อต x และ y_avg ด้วย plot()
- วาง legend บนรูปภาพ
- ใช้เมธอด show() เพื่อแสดงรูปภาพ
ตัวอย่างโค้ด
import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.array([3, 4, 5, 6, 7, 8, 9]) y = np.array([6, 5, 4, 3, 2, 1, 6]) fig, ax = plt.subplots() ax.plot(x, y, 'o-', label='line plot') y_avg = [np.mean(x)] * len(x) ax.plot(x, y_avg, color='red', lw=6, ls='--', label="average plot") plt.legend(loc=0) plt.show()
ผลลัพธ์
