ในการทำเครื่องหมาย (annotate) ค่าสูงสุดใน Pyplot เราสามารถทำตามขั้นตอนต่อไปนี้:
- ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
- สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่
- สร้างลิสต์ของ x และ y จุดข้อมูล
- พลอต x และ y ด้วย numpy
- หาค่าสูงสุดในอาร์เรย์ Y และตำแหน่งที่ตรงกับองค์ประกอบ max นั้นในอาร์เรย์
- ทำเครื่องหมายจุดนั้นด้วย local max
- เพื่อแสดงรูป ใช้เมธอด 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()
ax = fig.add_subplot(111)
x = np.array([1, 3, 5, 3, 1])
y = np.array([2, 1, 3, 1, 2])
line, = ax.plot(x, y)
ymax = max(y)
xpos = np.where(y == ymax)
xmax = x[xpos]
ax.annotate('local max', xy=(xmax, ymax), xytext=(xmax, ymax + 5), arrowprops=dict(facecolor='black'))
plt.show()
ผลลัพธ์
