'How to add some text with relative coordinate on a plot already created?
I have this plot :
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 :

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 !
Solution 1:[1]
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
Solution 2:[2]
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')
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | david |
| Solution 2 | Davide_sd |
| Solution 3 | Z-Y.L |

