0

I add some information in a Python plot (with import matplotlib.pyplot as plt), using this code:

plt.text(0.0, 20000.0, r'$[R^2 = %s]$'% (round(R2,4)), fontsize=16)
plt.text(0.0, 22500.0, r'$[y = %s x]$'% (round(slope[0][0],4)), fontsize=16)

The values inserted in the plot, R2 and slope[0][0] have been previously calculated.

This works perfectly fine, but in order to insert the 2 values of R2 and slope at different places, I need 2 calls of plt.text.

I wonder whether it would be possible to use just 1 call? I guess I would have to add \n somewhere in order to have the 2 texts aligned one below the other, but I don't understand the right syntax to use.

Any ideas?

Andrew
  • 926
  • 2
  • 17
  • 24
  • 1
    Does this answer your question? [Python : Matplotlib annotate line break (with and without latex)](https://stackoverflow.com/questions/10284847/python-matplotlib-annotate-line-break-with-and-without-latex) – Jongware May 03 '20 at 16:28
  • Yes! Thank you. I thought I could use `plt.text` instead of using `plt.annotate`, but anyway, since it works, it's good. – Andrew May 03 '20 at 17:28

1 Answers1

0

You can use plt.text and use \n as you guessed. Just be careful with the r prefix which treats \n as a raw \ and n, not a newline escape character. A workaround is to put the LaTeX and newline in separate strings separated by a space (which Python automatically concatenates):

plt.plot([0,1], [0,1])
plt.text(0.2, 0.6, 'Line 1\nLine 2')
plt.text(0.6, 0.2, r'$L_1$' '\n' '$L_2$')

enter image description here

stevemo
  • 1,077
  • 6
  • 10