如何在 Pyplot 中自動添加註釋,表示最大值?


要為 Pyplot 中的最大值添加註釋,我們可以執行以下步驟 -

  • 設定圖形大小並調整子圖之間和周圍的填充。
  • 建立一個新圖形或啟用一個現有的圖形。
  • 建立一個列表,其中包含 xy 資料點。
  • 使用 numpy 繪製 xy 資料點。
  • 找出 Y 陣列中的最大值及陣列中對應於該 最大值 元素的位置
  • 使用區域性最大值對該點添加註釋。
  • 要顯示圖形,請使用 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()

輸出

更新時間: 2021 年 7 月 9 日

7K+ 檢視次數

開啟你的 職業旅程

完成課程,獲得認證

開始
廣告
© . All rights reserved.