LaTeX not working on matplotlib text - python

I've been having this trouble for a long time whenever I want to render LaTeX for plot labelling and text, it works sometimes for some symbols but not others. For example in my script shown here generates the plot below:
from matplotlib import rc
plt.rc('text', usetex=True)
plt.plot(a_t,asol[:,0],label ='$\psi$')
plt.plot(a_t,rho,label ="$\rho/\rho_c$")
plt.xlabel(r"$\xi$",fontsize=15)
from matplotlib.legend_handler import HandlerLine2D
plt.legend(loc='upper left',prop={'size':12},numpoints=1)
I've tried other symbols, $\pi$ works okay but $\theta$ only shows "heta" without the t. I'm confused by why some symbols works for LaTeX and some don't.
Thanks!

Remember that certain characters in Python strings have special meanings, e.g. \r for carriage return, \t for tab. That's why you're only getting the strange results some of the time, since \p doesn't have a special meaning. So either make sure your backslashes are treated as literal backslashes by escaping them:
plt.plot(a_t,rho,label = "$\\rho/\\rho_c$")
Or use raw strings:
plt.plot(a_t,rho,label = r"$\rho/\rho_c$")

Related

Plots with unicode character

I need to put greek letters in labels of a matplotlib plot . how can I do it? For instance, unicode Omega is : u\u03A9. I use plt.xlabel('label')
If you are looking specifically for greek letter, you can use LaTex in-line math formatting commands (i.e. '$\Omega$') to produce letter that are in the Latex character map.
import numpy as np
import matplotlib.pyplot as plt
plt.plot(np.arange(1000), np.random.rand(1000), 'b.')
plt.xlabel('$\Omega$', size=16)
Here are good resources for finding LaTex symbols.
PDF list: https://www.rpi.edu/dept/arc/training/latex/LaTeX_symbols.pdf
Draw your symbol, get a bunch of LaTex characters: http://detexify.kirelabs.org/classify.html
I'm not positive about matplotlib, but I would assume that declaring them as unicode strings should work
>>> print u'\u03A9'
Ω

Pyplot annotation: roman numerals

In a python plot, I would like to put annotations in with Roman numerals. I.e., "I", "II", "III" and "IV".
Now, the straightforward thing to do is to simply use strings as "I", "II", etc., but I would like them to be typeset specifically as Roman numerals (so, including the horizontal bar on top and below of the III, for instance.
The difficulty is mainly that using LateX commands, as I would do for other symbols (e.g. \alpha), doesn't seem possible because if one wants to use Roman numerals in LateX it is common practice to define a new command and I wouldn't know how to incorporate that within the python environment.
Any ideas?
This is possible, by placing your LaTeX \newcommand in the text.latex.preamble in plt.rcParams. Here I use the command for Roman Numerals from the answer you linked to. To help with the escaping of LaTeX characters, we can use raw strings to make thing easier (preface the string with the r character).
import matplotlib.pyplot as plt
# Turn on LaTeX formatting for text
plt.rcParams['text.usetex']=True
# Place the command in the text.latex.preamble using rcParams
plt.rcParams['text.latex.preamble']=r'\makeatletter \newcommand*{\rom}[1]{\expandafter\#slowromancap\romannumeral #1#} \makeatother'
fig,ax = plt.subplots(1)
# Lets try it out. Need to use a 'raw' string to escape
# the LaTeX command properly (preface string with r)
ax.text(0.2,0.2,r'\rom{28}')
# And to use a variable as the roman numeral, you need
# to use double braces inside the LaTeX braces:
for i in range(1,10):
ax.text(0.5,float(i)/10.,r'\rom{{{}}}'.format(i))
plt.show()

How can I write the latex special character $\bar{T}$ in matplotlib axes?

I would like to write the latex math mode symbol $\bar{T}$ in the axes label of a plot made with matplotlib. The documentation states that math mode is not supported so I tried
plt.xlabel(r'$\displaystyle \={T}$',fontsize=12)
and
plt.xlabel(r'$\={T}$',fontsize=12)
which gives the errors
matplotlib.pyparsing.ParseFatalException: Expected end of math '$'
$\displaystyle \={T}$ (at char 0), (line:1, col:1)
and
raise ParseFatalException(msg + "\n" + s)
matplotlib.pyparsing.ParseFatalException: Expected end of math '$'
$\={T}$ (at char 0), (line:1, col:1)
>>>
Is there a way to write this symbol in the axes labels using matplotlib? I have been able to write other latex axes labels but I have never used any of these special characters.
The documentation page you linked to was describing calling out to Latex to provide formatted text, but matplotlib has its own builtin math expression parser that can deal with most Latex math commands just fine, without actually running an external latex command. Unless you've specifically set up your matplotlib install to use an external install of Latex, you're still using the builtin math parser, which can deal with \bar{} just fine:
plt.plot(range(5), range(5))
plt.xlabel(r'$\bar{T}$',fontsize=12)
plt.show()

\frac{}{} won't work for me w/ pylab

I'm rather new at using python and especially numpy, and matplotlib. Running the code below (which works fine without the \frac{}{} part) yields the error:
Normalized Distance in Chamber ($
rac{x}{L}$)
^
Expected end of text (at char 32), (line:1, col:33)
The math mode seems to work fine for everything else I've tried (symbols mostly, e.g. $\mu$ works fine and displays µ) so I'm not sure what is happening here. I've looked up other peoples code for examples and they just seem to use \frac{}{} with nothing special and it works fine. I don't know what I'm doing differently. Here is the code. Thanks for the help!
import numpy as np
import math
import matplotlib.pylab as plt
[ ... bunch of calculations ... ]
plt.plot(xspace[:]/L,vals[:,60])
plt.axis([0,1,0,1])
plt.xlabel('Normalized Distance in Chamber ($\frac{x}{L}$)')
plt.savefig('test.eps')
Also, I did look up \f and it seems its an "escape character", but I don't know what that means or why it would be active within TeX mode.
In many languages, backslash-letter is a way to enter otherwise hard-to-type characters. In this case it's a "form feed". Examples:
\n — newline
\r — carriage return
\t — tab character
\b — backspace
To disable that, you either need to escape the backslash itself (backslash-backslash is a backslash)
'Normalized Distance in Chamber ($\\frac{x}{L}$)'
Or use "raw" strings where escape sequences are disabled:
r'Normalized Distance in Chamber ($\frac{x}{L}$)'
This is relevant to Python, not TeX.
Documentation on Python string literals
"\f" is a form-feed character in Python. TeX never sees the backslash because Python interprets the \f in your Python source, before the string is sent to TeX. You can either double the backslash, or make your string a raw string by using r'Normalized Distance ... etc.'.
You have to add an r front of the string to avoid parsing the \f.

using the symbol font for Greek symbols in TeX via matplotlib

To annotate my figures with Greek letters in the matplotlib package of Python, I use the following:
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcParams['ps.useafm'] = True
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
plt.rcParams['pdf.fonttype'] = 42
# plot figure
# ...
# annotate figure
plt.xlabel(r'$\mu$ = 50')
plt.ylabel(r'$\sigma$ = 1.5')
This makes the equal symbol and everything to the right of it in the Helvetica font, as intended, and the Greek symbols default to the usual TeX font (which I believe is Times New Roman.)
How can I make it so the font used for the Greek letters is the "Symbol" font instead? It's important for me not to have it appear in the default Times font of TeX.
thanks for your help.
Funny you should ask this; I've been struggling with similar problems not too long ago. Considering how complicated font handling is in TeX, I'd sidestep TeX altogether.
However, any decent Helvetica has the Greek letters built-in, so you don't need to use the Symbol font. Just put some Unicode code points into your string, like this:
plt.xlabel(u'\u03bc = 50')
plt.ylabel(u'\u03c3 = 1.5')
For finding the code points, this Unicode codepoint lookup/search tool is really convenient.
I'm not sure if and how matplotlib handles Unicode strings. If the above fails, encode in some encoding that matplotlib expects.
(If you really insist on using Symbol: I don't think you can use multiple fonts within the same label, so then you'll have to add multiple labels and write some code to align them to each other. It's not pretty, but it can be done.)

Categories