Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get error while trying to use LaTeX in plots' label

I try to show:

enter image description here

...as my plots' x axis label. For this purpose I use the pylab.figtext() function, i.e:

py.figtext(0.5, 0.05, "$k=2,\left \langle \left | -k \right |;k \right \rangle, 
k\in \mathbb{N}_{+}\cup\left \{ 0 \right \}$", rotation='horizontal', size='12')

Unfortunately, I get error:

ValueError: 
$k=2,\left \langle \left | -k 
ight |;k 
ight 
angle, k\in \mathbb{N}_{+}\cup\left \{ 0 
ight \}$
^
Expected end of text (at char 0), (line:1, col:1)

Why is that? I thought, that I can use LaTeX freely. How should I format my text in figtext() method in order to achieve the aforementioned mathematical sentence? Thank you in advance.

like image 980
bluevoxel Avatar asked Dec 14 '14 21:12

bluevoxel


2 Answers

This can be fixed by a 1 letter correction:

py.figtext(0.5, 0.05, r"$k=2,\left \langle \left | -k \right |;k \right \rangle, 
k\in \mathbb{N}_{+}\cup\left \{ 0 \right \}$", rotation='horizontal', size='12')

Note the r before the string literal. The cause of the error is that several of the character combinations in your latex string are valid Python escape sequences for such things as tabs and new-lines. A string literal prefixed with an r (e.g. r"foo\nbar") makes Python interpret the string as a raw string literal, i.e. without converting the escaped character combinations to special characters.

like image 186
Bas Swinckels Avatar answered Sep 20 '22 20:09

Bas Swinckels


The backslashes in your string are interpreted as Python string escapes. For instance \r is interpreted as a carriage return. Use a raw string by making your string r"$k=2,\left \langle \left...".

like image 27
BrenBarn Avatar answered Sep 22 '22 20:09

BrenBarn