How to automatically annotate maximum value in pyplot

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to automatically annotate maximum value in pyplot in Python. So Here I am Explain to you all the possible Methods here.

How to automatically annotate maximum value in pyplot?

1. How to automatically annotate maximum value in pyplot?

I don't have data of macrodata.csv to go with. However, generically, assuming you have x and y axis data as an list, you can use following method to get auto positioning of max.

2. automatically annotate maximum value in pyplot

I don't have data of macrodata.csv to go with. However, generically, assuming you have x and y axis data as an list, you can use following method to get auto positioning of max.

Method 1

If x and y are the arrays to plot, you get the coordinates of the maximum via

xmax = x[numpy.argmax(y)]
ymax = y.max()

This can be incorporated into a function that you may simply call with your data.

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()

Method 2

I don’t have data of macrodata.csv to go with. However, generically, assuming you have x and y axis data as an list, you can use following method to get auto positioning of max.

Working Code:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()

x=[1,2,3,4,5,6,7,8,9,10]
y=[1,1,1,2,10,2,1,1,1,1]
line, = ax.plot(x, y)

ymax = max(y)
xpos = y.index(ymax)
xmax = x[xpos]

ax.annotate('local max', xy=(xmax, ymax), xytext=(xmax, ymax+5),
arrowprops=dict(facecolor='black', shrink=0.05),
)

ax.set_ylim(0,20)
plt.show()

Plot :

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.