[Tex/LaTex] Can’t save image as eps in matplotlib when using tex since new install

epsmatplotlibpython

I want to save a plot from matplotlib as an eps file, which has worked previously with no problem. However, today I reinstalled latex and ever since, I have trouble with eps. I have the following MWE

import matplotlib.pyplot as plt
from matplotlib import rc

rc('text', usetex=True)
fig, ax = plt.subplots()
ax.plot(0,0, label = r'$8$')
plt.savefig('plot.jpg')
plt.savefig('plot.eps')
plt.close()

that does not produce an error message. The jpg is saved correctly, but the eps file is just plain white. I tried uninstalling and reinstalling latex with

sudo apt-get remove dvipng texlive-latex-extra texlive-fonts-recommended texmf texlive tex-common cm-super
sudo apt-get install dvipng texlive-latex-extra texlive-fonts-recommended cm-super

but still have the same problem. I am using Ubuntu 18.04.4, Matplotlib 3.2.1, Python 3.6.9. I tried running the script via Spyder and via command line, neither worked. Does anyone know what could be the problem?

I inserted the tex file generated in matplotlib.cache into a latex editor and it did not compile, instead gave an error unknown graphics extension ps for the line \includegraphics*[angle=0]{/tmp/tmpnu3znvkl/tmp.ps}. Could the problem be that somehow latex confuses ps and eps?

Best Answer

I'm experiencing the same frustrating problem, but here's a workaround if you're using a unix/linux machine. At least, this worked for me on MacOS.

  • Save the file as in .ps instead of .eps via plt.savefig(); do not use bbox_inches="tight" or some of the figure might get clipped later.
  • Convert the .ps files to .eps via ps2eps on the command line.

Python part:

import matplotlib.pyplot as plt

plt.rc('text', usetex=True)
plt.rc('legend', frameon=False) # PS doesn't do well with transparencies

fig, ax = plt.subplots()
ax.plot([0,1,2], [0,1,2], label=r'$y = mx + b$')  # Latex legend label.
ax.text(1, 0, r"$e^{ix} = \cos(x) + i\sin(x)$")   # More Latex text.
ax.legend(loc="upper left")

plt.savefig('plot.ps')          # Postscript, not Encapsulated Postscript

Now in the command line,

$ ps2eps -g plot.ps

That should create a plot.eps file that you can open and check. When I open it with Preview (MacOS), it converts it to a PDF that looks like this (which I then had to convert to a PNG to upload to this site).

plot.eps

Related Question