如何自动注释 Pyplot 中的最大值?
pythonserver side programmingprogramming更新于 2025/8/8 23:40:17
要注释 Pyplot 中的最大值,我们可以采取以下步骤 −
- 设置图形大小并调整子图之间和周围的填充。
- 创建一个新图形或激活现有图形。
- 列出 x 和 y 数据点。
- 使用 numpy 绘制 x 和 y 数据点。
- 在 Y 数组中找到最大值并对应于数组中该 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()
输出

相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

