Matplotlib:annotate()缺少一个必需的位置参数:“self”。

3

我是一个matplotlib的新手,想给图表中的一个点设置文本,但是我遇到了以下错误:

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()缺少一个必需的位置参数'self'

我的代码如下:

import matplotlib.axes as Axes

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

df是之前由 Pandas 生成的 DataFrame。

我做错了什么?我遵循一些教程和文档,但是我找不到错误。


plt.annotate(xy=(df[0:1]["ortg"], df[0:1]["drtg"]), s="Message") 这个怎么样? - Péter Leéh
2个回答

4

您不能直接从类中调用非静态方法。需要先实例化axes对象。

有很多种方法可以获取Axes实例。一种简单而紧凑的方式是:

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

4
你不能直接从类中导入它。
简而言之:
fig, ax = plt.subplots()
ax.annotate(.....)

示例(来自文档):

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

参考:https://matplotlib.org/3.1.1/api/_as-gen/matplotlib.axes.Axes.annotate.html

该函数添加文本注释到Axes。文本位置由`xy`指定,注释的文本由`s`指定。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接