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

Time:04-12

I have this plot : enter image description here made with :

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

I would like to add text on a specific coordinate like this : enter image description here

I tryed with :

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

but it goes on the plot already shown.. How can I merge it ?

Thanks !

CodePudding user response:

I suggest you first, before any plotting command, define usual fig and ax variables:

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

and you use the ax object in your plot call that, I suppose, is from pandas so:

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

then use ax.text instead of plt.text:

ax.text(...your_arguments

CodePudding user response:

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

CodePudding user response:

If you mean to put the "matplotlib" text in the same position as the second one, then you can use the ax.transAxes transformer.

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

enter image description here

  • Related