python - 如何在pyplot中自动标注最大值

标签 python pandas numpy matplotlib

我想弄清楚如何在图形窗口中自动注释最大值。我知道您可以通过手动输入 x、y 坐标来使用 .annotate() 方法注释您想要的任何点来执行此操作,但我希望注释是自动的,或者找到最大点自己。

到目前为止,这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import Series, DataFrame

df = pd.read_csv('macrodata.csv') #Read csv file into dataframe
years = df['year'] #Get years column
infl = df['infl'] #Get inflation rate column

fig10 = plt.figure()
win = fig10.add_subplot(1,1,1)
fig10 = plt.plot(years, infl, lw = 2)

fig10 = plt.xlabel("Years")
fig10 = plt.ylabel("Inflation")
fig10 = plt.title("Inflation with Annotations")

Here's the figure that it generates

最佳答案

如果 xy 是要绘制的数组,您可以通过

获得最大值的坐标
xmax = x[numpy.argmax(y)]
ymax = y.max()

这可以合并到一个函数中,您可以简单地用您的数据调用该函数。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-2,8, num=301)
y = np.sinc((x-2.21)*3)


fig, ax = plt.subplots()
ax.plot(x,y)

def annot_max(x,y, ax=None):
    xmax = x[np.argmax(y)]
    ymax = y.max()
    text= "x={:.3f}, y={:.3f}".format(xmax, ymax)
    if not ax:
        ax=plt.gca()
    bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
    arrowprops=dict(arrowstyle="->",connectionstyle="angle,angleA=0,angleB=60")
    kw = dict(xycoords='data',textcoords="axes fraction",
              arrowprops=arrowprops, bbox=bbox_props, ha="right", va="top")
    ax.annotate(text, xy=(xmax, ymax), xytext=(0.94,0.96), **kw)

annot_max(x,y)


ax.set_ylim(-0.3,1.5)
plt.show()

enter image description here

关于python - 如何在pyplot中自动标注最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43374920/

相关文章:

python - 删除行值类似于 '[ ]' 的数据框列

python - 沿 Pandas 数据帧行传播计算

python - tensorflow 中 numpy.newaxis 的替代方案是什么?

python - 以复数矩阵作为初始值求解 python 中的 ode

python - Pandas groupby 多列,多列列表

python - 计算 A* 寻路算法的执行时间时,Python 列表中缺少项目

python - Pandas groupby中的条件分配

python - ValueError : The field admin. LogEntry.user 是用惰性引用声明的

python - 在 Python Pandas 中格式化字符串数字

python - 保留基于另一个数组的数组中的唯一值,同时保留顺序