如何在 Pyplot 中自动添加注释,表示最大值?
要为 Pyplot 中的最大值添加注释,我们可以执行以下步骤 -
- 设置图形大小并调整子图之间和周围的填充。
- 创建一个新图形或激活一个现有的图形。
- 创建一个列表,其中包含 x 和 y 数据点。
- 使用 numpy 绘制 x 和 y 数据点。
- 找出 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()输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP