如何自动注释 Pyplot 中的最大值?
要注释 Pyplot 中的最大值,我们可以采取以下步骤−
- 设置图形大小和子图之间和周围的填充。
- 创建一个新图或激活现有图。
- 创建 x 和 y 数据点的列表。
- 使用numpy绘制 x 和 y 数据点。
- 在Y数组中找到最大值和对应的位置。其中,位置即为数组中的 max 元素。
- 用局部最大值注释该点。
- 使用 show() 方法显示图形。
阅读更多:Python 教程
例子
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()
极客教程