9

Matplotlib doesn't seem to find files in the current working directory when running latex. Does anyone know where it looks for files?

The background is: I have a huge preamble that I \input into latex before processing (lots of macros, various usepackages, etc.). In a stand-alone paper, I do \input{BigFatHeader.tex}. So when I use matplotlib, I try to just input this file in the preamble. The python code to do this is

matplotlib.rcParams['text.latex.preamble'].append(r'\input{BigFatHeader.tex}')

And I can verify that that file is in the cwd -- I see it when I ls, or I can do os.path.isfile("BigFatHeader.tex") and get True. But when I try to plot something using latex, python spits out a big error message from the latex process, that culminates in ! LaTeX Error: File BigFatHeader.tex not found. So presumably it changes to some other directory (not /tmp/; I checked) to do its work. Any idea where this might be?

My minimal working example is:

import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['text.latex.preamble'] = r'\input{BigFatHeader.tex}'
matplotlib.rcParams['text.usetex'] = True
plt.plot([1,2])
plt.savefig('MWE.pdf')

Where BigFatHeader.tex might be as simple as

\usepackage{bm}
Mike
  • 19,114
  • 12
  • 59
  • 91
  • Not that this helped solve my problem, but in case anyone is curious, the working directory in my installation turned out to be `~/.matplotlib/tex.cache/`. – Mike Feb 11 '12 at 20:23

1 Answers1

9

I'm having the same error on my Ubuntu Lucid, matplotlib 1.1.0. There are two options:

Giving it a full path:

matplotlib.rcParams['text.latex.preamble'] = r'\input{/home/br/sweethome/temp/BigFatHeader}'

works for me. Notice that you don't put .tex extension for the files to be \input. If you don't want to hardcode the path, you can get it using os.getcwd():

import matplotlib
import matplotlib.pyplot as plt
import os

filename=r'\input{'+os.getcwd()+r'/BigFatHeader}'

matplotlib.rcParams['text.latex.preamble'] = filename
matplotlib.rcParams['text.usetex'] = True
plt.plot([1,2])
plt.savefig('MWE.pdf')

Or just read in your your file into a text string and set the rcParams with it.

import matplotlib
import matplotlib.pyplot as plt

paramstring=r'\usepackage{bm}'
matplotlib.rcParams['text.latex.preamble'] = paramstring
matplotlib.rcParams['text.usetex'] = True
plt.plot([1,2])
plt.savefig('MWE.pdf')
ev-br
  • 24,968
  • 9
  • 65
  • 78
  • That works. I also hadn't thought of reading the file into a string and adding it to the preamble string. Thanks! – Mike Feb 11 '12 at 20:22
  • I am trying to figure out a way to do this in the matplotlibrc file, as I have many plotting scripts that all need the same preamble. Any ideas? – japreiss Nov 26 '20 at 03:38