# Using Latex in Matplotlib plot title/axis label [closed]

Sorry if this is a repost; I'm sure this question gets asked often but I couldn't find exactly what I was after in the search. I'm trying to write a scientific plotting program in matplotlib (using python 2.7) and I'm having trouble getting it to recognise LaTeX code the way I expect.

On the matplotlib site, there is an example which works perfectly on my machine (Ubuntu 12.04):

    from matplotlib import rc
from numpy import arange, cos, pi
from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, \
grid, savefig, show

rc('text', usetex=True)
rc('font', family='serif')
figure(1, figsize=(6,4))
ax = axes([0.1, 0.1, 0.8, 0.7])
t = arange(0.0, 1.0+0.01, 0.01)
s = cos(2*2*pi*t)+2
plot(t, s)

xlabel(r'\textbf{time (s)}')
ylabel(r'\textit{voltage (mV)}',fontsize=16)
title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
fontsize=16, color='r')
grid(True)
savefig('tex_demo')

show()


But when I try and apply the concepts from this to my existing code, things go awry. My code is reading in values from a text file to use as strings for the titles and axes for a series of subplots. the text file looks like this only one line break per line in the original:

Example \texit{plot title}

x label

y label

So I'm expecting everything to be ordinary except "plot title", which should be italic. Here is the function that I have written:

from matplotlib import rc

...
def plot_graphic(formatting_file):
rc('text', usetex=True)
rc('font', family='serif')
formatting = open(formatting_file)
title_text = data[0]
sup_title_size = 20
title_size = int(0.75*sup_title_size)
x_axis_label = data[1]
y_axis_label = data[2]
plt.subplot(224)
plt.plot(n.x, o, n.x, s, "r")
plt.title("Original and Smoothed Data", fontsize=title_size)
plt.xlabel(x_axis_label)
plt.ylabel(y_axis_label)
plt.subplot(221)
plt.plot(n.x, o)
plt.title("Original Data", fontsize=title_size)
plt.xlabel(x_axis_label)
plt.ylabel(y_axis_label)
plt.subplot(223)
plt.plot(n.x, s, "r")
plt.title("Smoothed Data", fontsize=title_size)
plt.xlabel(x_axis_label)
plt.ylabel(y_axis_label)
plt.subplot(222)
plt.plot(gx, gy, "k.-")
plt.title("Smoothing Window", fontsize=title_size)
plt.xlabel(x_axis_label)
plt.ylabel("Window Function")
plt.suptitle(title_text, fontsize=sup_title_size)
plt.show()
formatting.close()


Where "formatting_file" is a string (path to the file with the above contents), and everything works as expected without the Tex formatting attempt (if I remove the lines starting with rc). When I run this, however, I get a wall of tracebacks ending with:

RuntimeError: LaTeX was not able to process the following string:
''
Here is the full report generated by LaTeX:

This is pdfTeX, Version 3.1415926-1.40.10 (TeX Live 2009/Debian)
entering extended mode
(./65d362bbbe189488f3ed27a3ef3526ff.tex
LaTeX2e <2009/09/24>
Babel <v3.8l> and hyphenation patterns for english, usenglishmax, dumylang, noh
(/usr/share/texmf-texlive/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texmf-texlive/tex/latex/base/size10.clo))
(/usr/share/texmf-texlive/tex/latex/type1cm/type1cm.sty)
(/usr/share/texmf-texlive/tex/latex/psnfss/helvet.sty
(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty))
(/usr/share/texmf-texlive/tex/latex/psnfss/courier.sty)
(/usr/share/texmf-texlive/tex/latex/base/textcomp.sty
(/usr/share/texmf-texlive/tex/latex/base/ts1enc.def))
(/usr/share/texmf-texlive/tex/latex/geometry/geometry.sty
(/usr/share/texmf-texlive/tex/generic/oberdiek/ifpdf.sty)
(/usr/share/texmf-texlive/tex/generic/oberdiek/ifvtex.sty)

Package geometry Warning: Over-specification in h'-direction.
width' (5058.9pt) is ignored.

Package geometry Warning: Over-specification in v'-direction.
height' (5058.9pt) is ignored.

) (./65d362bbbe189488f3ed27a3ef3526ff.aux)
(/usr/share/texmf-texlive/tex/latex/base/ts1cmr.fd)
(/usr/share/texmf-texlive/tex/latex/psnfss/ot1pnc.fd)
*geometry auto-detecting driver*
*geometry detected driver: dvips*
(./65d362bbbe189488f3ed27a3ef3526ff.aux) )
No pages of output.
Transcript written on 65d362bbbe189488f3ed27a3ef3526ff.log.


It boils down to this: I don't have a lot of experience with LaTeX, but I'm trying to learn, so I don't understand these errors. I don't understand why my code doesn't work when it doesn't seem to be an awful lot different from the example which does. For reference, I have also tried this on an x86 Windows 7 machine with the same result.

What am I missing?

EDIT:

I suppose the code snippet I supplied for my example is excessively long. A shorter, simpler version would be along these lines:

import matplotlib.pyplot as plt
from matplotlib import rc

rc('text', usetex=True)
rc('font', family='serif')

data = ["Example \texit{plot title}\n", "x label", "y label"]
title_text = data[0]
x_axis_label = data[1]
y_axis_label = data[2]

plt.plot([1,2,3,4],[1,2,3,4])
plt.title(title_text)
plt.xlabel(x_axis_label)
plt.ylabel(y_axis_label)
plt.show()

-

## closed as off topic by lockstep, Kurt, Claudio Fiandrino, Seamus, ThorstenJan 17 '13 at 16:50

Questions on TeX - LaTeX Stack Exchange are expected to relate to TeX, LaTeX or related typesetting systems within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here. If this question can be reworded to fit the rules in the help center, please edit the question.

Welcome to TeX.sx! It would be very useful to have a complete Minimal Working Example (MEW) of LaTeX code that generates the error so that people can reproduce it and possibly find solutions. –  Peter Jansson Jan 17 '13 at 11:21
Hi Peter, thanks for the welcome. I've edited the question and added a shorter code snippet which should work independently to show what I'm trying to do. Do you think this would have been better posted to a different stackexchange (i.e. one dealing more with programming in python)? –  Magic_Matt_Man Jan 17 '13 at 11:30
I can't test your code but I assume \texit which you have in several places is a typo for \textit which would make italic text and is used in the first template that you show. –  David Carlisle Jan 17 '13 at 12:02
Thanks for pointing that out. I've made the change but still get the RunTimeError. –  Magic_Matt_Man Jan 17 '13 at 12:18

I think your problem is newline characters read in from the file. Try removing them with rstrip(). That will fix your short example. Maybe something like this for your longer code:

title_text = data[0].rstrip('\r\n')
sup_title_size = 20
title_size = int(0.75*sup_title_size)
x_axis_label = data[1].rstrip('\r\n')
y_axis_label = data[2].rstrip('\r\n')


By the way, matplotlib 1.2 added a pgf backend, so that may be something you want to look into.

-
Thank you for your answer. I did have rstrip in there at one point before, but obviously my implementation of it was flawed. I copied your suggestion in and it no longer throws the exception- the text still doesn't quite render as I expected, but at least it renders. One final note: sorry for posting this in the wrong stackexchange; I knew I was pushing my luck a little but I thought it was still close enough to TeX topics. I'll try and avoid that in future. –  Magic_Matt_Man Jan 18 '13 at 10:21