José Carlos
José Carlos

Reputation: 2932

Matplotlib: annotate() missing 1 required positional argument: 'self'

I'm newbie in matplotlib and I'm trying to set a text to a point in a graph but I've got the error:

Traceback (most recent call last): File "main.py", line 239, in main() File "main.py", line 232, in main p.show_graphic_ortg_drtg() File "/home/josecarlos/Workspace/python/process/process.py", line 363, in show_graphic_ortg_drtg Axes.Axes.annotate(xy=(df[0:1]["ortg"], df[0:1]["drtg"]), s="Hola") TypeError: annotate() missing 1 required positional argument: 'self'

My code is:

import matplotlib.axes as Axes

Axes.Axes.annotate(xy=(df[0:1]["ortg"], df[0:1]["drtg"]), s="Message")

df is a DataFrame from Pandas previously generated.

What am I doing wrong? I'm following some tutorials and documentation and I don't find the mistake.

Upvotes: 3

Views: 23309

Answers (2)

seralouk
seralouk

Reputation: 33207

You cannot import it directly from the class.

Briefly:

fig, ax = plt.subplots()
ax.annotate(.....)

Example (Taken from the documentation):

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)

ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05),
            )
ax.set_ylim(-2, 2)
plt.show()

Ref: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.annotate.html

Upvotes: 4

Diziet Asahi
Diziet Asahi

Reputation: 40747

You cannot call a non static method directly from the class. You need to instanciate the axes object first.

There are many ways to get an Axes instance. A simple and compact way is:

fig, ax = plt.subplots()
# this function returns an instance of the Figure class
# and an instance of the Axes class.
ax.annotate(...)
# call annotate() from the Axes instance

Upvotes: 5

Related Questions