[Tex/LaTex] Using Latex in Matplotlib plot title/axis label


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')


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)
    data = formatting.readlines()
    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.plot(n.x, o, n.x, s, "r")
    plt.title("Original and Smoothed Data", fontsize=title_size)
    plt.plot(n.x, o)
    plt.title("Original Data", fontsize=title_size)
    plt.plot(n.x, s, "r")
    plt.title("Smoothed Data", fontsize=title_size)
    plt.plot(gx, gy, "k.-")
    plt.title("Smoothing Window", fontsize=title_size)
    plt.ylabel("Window Function")
    plt.suptitle(title_text, fontsize=sup_title_size)

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
LaTeX2e <2009/09/24>
Babel <v3.8l> and hyphenation patterns for english, usenglishmax, dumylang, noh
yphenation, loaded.
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class

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)
*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?


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]


Best Answer

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.