0

I want to put a text slightly above a horizontal line, the value of y where is variable, not a constant in a matplotlib figure. My current code is following:

fig, host = plt.subplots(figsize=(18,6))
plt.axhline(y = *a variable between 0-100*, color='r')
plt.text(*x-cord*, *y-cord* , '*Desired Text*', verticalalignment='bottom', horizontalalignment='right', transform=host.transAxes, color='red', fontsize=14)

However, the position of the text depends on x-coord, y-coord. As my horizontal line is a variable, every time I have to manually adjust the text position, which is not optimal for me to automate the figure creation.

JohanC
  • 71,591
  • 8
  • 33
  • 66
Debayan Paul
  • 95
  • 2
  • 9
  • You could use `transform=host.get_yaxis_transform()` to indicate the y-position via its y-value and the x-position in "axes coordinates" (0 at the very left, 1 at the right). – JohanC Dec 29 '22 at 14:33
  • You also might want to read the [difference between the pyplot and the object-oriented interface](https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interface/#pyplot-vs-object-oriented-interface). It helps readability and maintainability if you wouldn't mix them. – JohanC Dec 29 '22 at 14:42

0 Answers0