如何在已创建的绘图上添加一些具有相对坐标的文本?

How to add some text with relative coordinate on a plot already created?

我有这个情节: 用 :

制作
    serie_to_plot.plot(kind='barh', figsize=(8, 4), label='nombre de support avec une anomalie',xlabel='type d\'anomalie')
    right = 0.99
    top = 0.99
    plt.subplots_adjust(left=0.35, right=right, top=top, bottom=0.1)
    plt.legend()
    plt.show()

我想在特定坐标上添加文本,如下所示:

我试过:

    f = figure()
    ax = f.add_subplot(111)
    plt.text(right, top-0.2,'matplotlib',
     horizontalalignment='right',
     verticalalignment='top',
     transform = ax.transAxes)

但它继续在已经显示的情节中..我如何合并它?

谢谢!

我建议你首先,在任何绘图命令之前,定义通常的 figax 变量:

fig = plt.figure(figsize=(8, 4))
ax = fig.add_subplot()

并且您在 plot 调用中使用了 ax 对象,我想它来自 pandas 所以:

serie_to_plot.plot(kind='barh', 
                   ax=ax,
                   label='nombre de support avec une anomalie',xlabel='type d\'anomalie')

然后使用 ax.text 而不是 plt.text:

ax.text(...your_arguments
import pandas as pd

# generate some random data
df = pd.DataFrame({
    "Categories": ["A", "B", "C", "D", "E"],
    "Values": [1, 2, 3, 4, 5]
})

# capture the axis used by pandas for plotting
ax = df.plot(kind="barh", x="Categories")
right = 5
top = 2
# use that axis to add the text (or any other object)
ax.text(right, top, 'matplotlib',
     horizontalalignment='right',
     verticalalignment='top')

如果你想把“matplotlib”文本放在与第二个相同的位置,那么你可以使用ax.transAxes转换器。

import matplotlib.pyplot as plt
import pandas as pd

X = list('ABCDE')
Y = [1,2,3,4,5]

df = pd.DataFrame({'label':X, 'value':Y})

ax = df.plot(x='label', y='value', kind='barh', figsize=(8,4), label='label')

right = 0.99
top = 0.99
plt.subplots_adjust(left=0.35, right=right, top=top, bottom=0.1)

plt.legend()

plt.text(
    right, top-0.2, 'matplotlib',
    ha='right', va='top',
    transform=ax.transAxes)     # Specify the transformer