I’m trying to figure out how I can automatically annotate the maximum value in a figure window. I know you can do this by manually entering in x,y coordinates to annotate whatever point you want using the .annotate()
method, but I want the annotation to be automatic, or to find the maximum point by itself.
Here’s my code so far:
JavaScript
x
17
17
1
import matplotlib.pyplot as plt
2
import numpy as np
3
import pandas as pd
4
from pandas import Series, DataFrame
5
6
df = pd.read_csv('macrodata.csv') #Read csv file into dataframe
7
years = df['year'] #Get years column
8
infl = df['infl'] #Get inflation rate column
9
10
fig10 = plt.figure()
11
win = fig10.add_subplot(1,1,1)
12
fig10 = plt.plot(years, infl, lw = 2)
13
14
fig10 = plt.xlabel("Years")
15
fig10 = plt.ylabel("Inflation")
16
fig10 = plt.title("Inflation with Annotations")
17
Advertisement
Answer
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:
JavaScript
1
21
21
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
fig = plt.figure()
5
ax = fig.add_subplot(111)
6
7
x=[1,2,3,4,5,6,7,8,9,10]
8
y=[1,1,1,2,10,2,1,1,1,1]
9
line, = ax.plot(x, y)
10
11
ymax = max(y)
12
xpos = y.index(ymax)
13
xmax = x[xpos]
14
15
ax.annotate('local max', xy=(xmax, ymax), xytext=(xmax, ymax+5),
16
arrowprops=dict(facecolor='black', shrink=0.05),
17
)
18
19
ax.set_ylim(0,20)
20
plt.show()
21