How to automatically annotate the maximum value in a Pyplot?

To annotate the maximum value in a Pyplot, you can automatically find the peak point and add a text annotation with an arrow pointing to it. This is useful for highlighting important data points in your visualizations.

Steps to Annotate Maximum Value

  • Set the figure size and adjust the padding between and around the subplots
  • Create a new figure or activate an existing figure
  • Make a list of x and y data points
  • Plot x and y data points using matplotlib
  • Find the maximum in Y array and position corresponding to that max element in the array
  • Annotate that point with local max
  • To display the figure, use show() method

Example

Here's how to automatically find and annotate the maximum value in a plot ?

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 + 0.5), 
            arrowprops=dict(facecolor='black'))

plt.show()

How It Works

The code works by finding the maximum y-value using max(y), then locating its corresponding x-position with np.where(). The annotate() method places text at the specified coordinates with an arrow pointing to the maximum point.

Advanced Example with Multiple Peaks

For data with multiple maximum values, you can annotate all of them ?

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [8.00, 4.00]
plt.rcParams["figure.autolayout"] = True

x = np.array([1, 2, 3, 4, 5, 6, 7])
y = np.array([2, 3, 3, 1, 3, 2, 1])

plt.plot(x, y, 'b-o')

ymax = max(y)
xpos = np.where(y == ymax)[0]

for i, pos in enumerate(xpos):
    plt.annotate(f'Max {i+1}: ({x[pos]}, {y[pos]})', 
                xy=(x[pos], y[pos]), 
                xytext=(x[pos], y[pos] + 0.3),
                arrowprops=dict(facecolor='red', arrowstyle='->'))

plt.title('Annotating Multiple Maximum Values')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.grid(True, alpha=0.3)
plt.show()

Key Parameters

  • xy − The point to annotate (coordinates of the maximum)
  • xytext − Position where the text will be placed
  • arrowprops − Dictionary defining arrow appearance and style
  • fontsize − Size of the annotation text

Conclusion

Use max() and np.where() to find peak values, then annotate() to add labeled arrows. This technique automatically highlights the most important data points in your matplotlib visualizations.

---
Updated on: 2026-03-25T23:45:31+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements