Question

I want do use LaTex-signs in my matplotlib-figure. First I used.

pl.ylabel(r'$\pi \rho$',family='Courier New')

That was ok. But now the label I want to use is variable and comes from other *.py file. My idea was to import this file to the file from where the title comes:

import plot
YLabel = "$\pi \rho$"
plot(YLabel)

and in plot.py write:

pl.ylabel(r'%s' %(YLabel),family='Courier New')

But this Error appears:

ValueError: 
$\pi$ $
ho$
      ^
Expected end of text (at char 6), (line:1, col:7)

I already read Text rendering With LaTeX and Writing mathematical expressions from the docs of matplotlib, but it didnt help me.

Était-ce utile?

La solution

What's happening actually has nothing to do with the string formatting (i.e. calling x = "blah %s" % YLabel).

It's due to the way you initially define YLabel.

For example, try doing:

x = "\rho"
print x

The "\r" is interpreted as a carriage return and doesn't print. It just prints "ho". (This holds for a number of other escape sequences, e.g. \n, \t, \x, \f, \b, etc.)

To avoid this, you either need to define the original string as a "raw" string:

x = r"\rho"
print x

or explicitly escape the "\r" sequence:

x = "\\rho"
print x
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top