27

I have a very basic question : how to do a line break with matplotlib in python with an "annotate" command. I tried "\" and "\n" but it does not work. And how to do this for a "Latex" annotation and for a normal text annotation ?

Thank you very much.

Vincent
  • 57,703
  • 61
  • 205
  • 388
  • Possible duplicate of [Putting newline in matplotlib label with TeX in Python?](https://stackoverflow.com/questions/2660319/putting-newline-in-matplotlib-label-with-tex-in-python) – jdhao May 02 '18 at 07:16

4 Answers4

22

What exactly did you try?

Were you, by chance, using a raw string (e.g. r"whatever")?

'\n' works perfectly, but if you're using a raw string to avoid latex sequences being interpreted as an escape, it will be interpreted by python as '\' and 'n' instead of a newline.

As an example:

import matplotlib.pyplot as plt

plt.annotate('Testing\nThis\nOut', xy=(0.5, 0.5))

plt.show()

enter image description here

On the other hand, if we use a raw string:

import matplotlib.pyplot as plt

plt.annotate(r'Testing\nThis\nOut', xy=(0.5, 0.5))

plt.show()

enter image description here

Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • What if I want to move the text **outside** of the figure? Top left corner, for instance? – FaCoffee Nov 27 '15 at 10:48
  • 1
    @FC84 - In that case, specify the x,y position of the text in axes coordinates. For example, this would place text 5 _points_ to the right of the upper-right corner of the axes: `ax.annotate('blah', xy=(1, 1), xytext=(5, 0), xycoords='axes fraction', textcoords='offset points')` – Joe Kington Nov 27 '15 at 18:20
19

However, if you needed both, consider the following example:

import matplotlib.pyplot as plt

a = 1.23
b = 4.56

annotation_string = r"Need 1$^\mathsf{st}$ value here = %.2f" % (a) 
annotation_string += "\n"
annotation_string += r"Need 2$^\mathsf{nd}$ value here = %.2f" % (b)

plt.annotate(annotation_string, xy=(0.5, 0.5))

plt.show()

Which gives you:

enter image description here

The key is to assemble the string beforehand, using +=. That way, you can have the raw-string commands (indicated by r) and the line-break (\n) in the same annotation.

Schorsch
  • 7,761
  • 6
  • 39
  • 65
11

You can use the triple quotes when you define the annotation string, as in string="""some text""", so that the actual line breaks you type in your string will be interpreted as line breaks in the output. Here is an example, which includes latex and the printing of some numerical parameters from other parts of your code

import matplotlib.pyplot as plt

I = 100
T = 20

annotation_string = r"""The function plotted is:
$f(x) \ = \ \frac{{I}}{{2}} \cos\left(2 \pi \ \frac{{x}}{{T}}\right)$ 

where:
$I = ${0}
$T = ${1}""".format(I, T)

plt.annotate(annotation_string, xy=(0.05, 0.60), xycoords='axes fraction',
                                             backgroundcolor='w', fontsize=14)

plt.show()

I have added some "extras":

  • the r soon before the opening triple quotes, to facilitate the LaTeX interpreter

  • the double curly brackets {{}}, so that the .format() command and the LaTeX don't mess with each other

  • the xycoords='axes fraction' option, so to specify the position of the string with fractional values with respect of the width and height of the plot
  • the backgroundcolor='w' option, that puts a white marquee around the annotation (convenient in case of overlapping with your plot)

The plot obtained is this: enter image description here

Fabio
  • 1,132
  • 1
  • 13
  • 21
  • 1
    Why didn't the line `$I = ${0}` get interpreted as Latex between the 2 `$`s? – Jason Aug 31 '17 at 01:32
  • 1
    It did. I thought `.format()` uses `${}` as place holders. – Jason Aug 31 '17 at 01:44
  • Hi Jason, indeed, the "I = " between the dollar sign are interpreted by LaTeX, and they are plotted in italic. The numerical values are not, and are indeed not in italic. There is no particular reason why I left the numerical values out. Sorry if this created some confusion.. – Fabio Sep 29 '17 at 02:30
6

Quick solutions

plt.annotate("I am \n"+r"$\frac{1}{2}$"+"\n in latex math environment", xy=(0.5, 0.5))

Kind Stranger
  • 1,736
  • 13
  • 18
Ankit Kumar
  • 61
  • 1
  • 2