matplotlib
Plots in LaTeX¶
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
LaTeX installation is necessary (why?)
TODO: how to not specify fonts?
plt.rc('pgf', texsystem='lualatex') # or 'pdflatex' or 'xelatex' (default)
#plt.rc('text.latex', unicode=True)
#plt.rc('text', usetex=True)
plt.rc('font',
#family='serif',
serif=[],
#sans_serif=[],
monospace=[],
)
plt.rc('pgf', rcfonts=False)
# "pgf.preamble": [
# r"\usepackage{siunitx}", # use additional packages
# r"\usepackage{unicode-math}", # configure math fonts
# r"\setmathfont{XITS Math}",
# r"\setmainfont{Gentium}", # manually setting the main font
# ]
# 'text.latex.unicode': True,
# font.cursive
fig, ax = plt.subplots()
ax.plot([np.pi/2, np.pi, 0])
ax.set_title(r"An Experiment")
ax.set_xlabel(r"not sure what that means: $\sigma^2 < \epsilon$")
ax.set_ylabel(r"something with $\pi$")
ax.set_yticks([0, np.pi/2, np.pi])
ax.set_yticklabels([r"$0$", r"$\frac{\pi}{2}$", r"$\pi$"]);
fig.savefig('matplotlib_plot.pgf')
--------------------------------------------------------------------------- LatexError Traceback (most recent call last) <ipython-input-56-e943f1bd9f65> in <module>() ----> 1 fig.savefig('matplotlib_plot.pgf') /usr/lib/python3/dist-packages/matplotlib/figure.py in savefig(self, *args, **kwargs) 1468 self.set_frameon(frameon) 1469 -> 1470 self.canvas.print_figure(*args, **kwargs) 1471 1472 if frameon: /usr/lib/python3/dist-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 2192 orientation=orientation, 2193 bbox_inches_restore=_bbox_inches_restore, -> 2194 **kwargs) 2195 finally: 2196 if bbox_inches and restore_bbox: /usr/lib/python3/dist-packages/matplotlib/backends/backend_pgf.py in print_pgf(self, fname_or_fh, *args, **kwargs) 833 if is_string_like(fname_or_fh): 834 with codecs.open(fname_or_fh, "w", encoding="utf-8") as fh: --> 835 self._print_pgf_to_fh(fh, *args, **kwargs) 836 elif is_writable_file_like(fname_or_fh): 837 if not os.path.exists(fname_or_fh.name): /usr/lib/python3/dist-packages/matplotlib/backends/backend_pgf.py in _print_pgf_to_fh(self, fh, *args, **kwargs) 812 _bbox_inches_restore = kwargs.pop("bbox_inches_restore", None) 813 renderer = MixedModeRenderer(self.figure, w, h, dpi, --> 814 RendererPgf(self.figure, fh), 815 bbox_inches_restore=_bbox_inches_restore) 816 self.figure.draw(renderer) /usr/lib/python3/dist-packages/matplotlib/backends/backend_pgf.py in __init__(self, figure, fh, dummy) 420 421 # get LatexManager instance --> 422 self.latexManager = LatexManagerFactory.get_latex_manager() 423 424 if dummy: /usr/lib/python3/dist-packages/matplotlib/backends/backend_pgf.py in get_latex_manager() 230 if rcParams.get("pgf.debug", False): 231 print("creating LatexManager") --> 232 new_inst = LatexManager() 233 LatexManagerFactory.previous_instance = new_inst 234 return new_inst /usr/lib/python3/dist-packages/matplotlib/backends/backend_pgf.py in __init__(self) 320 stdout, stderr = latex.communicate(test_input.encode("utf-8")) 321 if latex.returncode != 0: --> 322 raise LatexError("LaTeX returned an error, probably missing font or error in preamble:\n%s" % stdout) 323 324 # open LaTeX process for real work LatexError: LaTeX returned an error, probably missing font or error in preamble: b"This is LuaTeX, Version beta-0.79.1 (TeX Live 2015/dev/Debian) (rev 4971) \n restricted \\write18 enabled.\n**LaTeX2e <2014/05/01>\nBabel <3.9l> and hyphenation patterns for 9 languages loaded.\n\n*(/usr/share/texlive/texmf-dist/tex/latex/base/minimal.cls\nDocument Class: minimal 2001/05/25 Standard LaTeX minimal class\n)\n(Please type a command or say `\\end')\n*\n*(/usr/share/texlive/texmf-dist/tex/latex/fontspec/fontspec.sty\n(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/expl3.sty\n(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/expl3-code.tex\n(/usr/share/texlive/texmf-dist/tex/latex/etex-pkg/etex.sty))\n(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3unicode-data.def)\n(/usr/share/texlive/texmf-dist/tex/latex/l3kernel/l3pdfmode.def))\n(/usr/share/texlive/texmf-dist/tex/latex/l3packages/xparse/xparse.sty)\n\n! LaTeX Error: File `luaotfload.sty' not found.\n\nType X to quit or <RETURN> to proceed,\nor enter new name. (Default extension: sty)\n\nEnter file name: \n! LaTeX Error: Missing \\begin{document}.\n\nSee the LaTeX manual or LaTeX Companion for explanation.\nType H <return> for immediate help.\n ... \n \nl.43 }\n \n 224 words of node memory still in use:\n 2 hlist, 33 glue_spec, 1 temp, 1 if_stack, 1 local_par, 1 dir nodes\n avail lists: 2:10,3:1,4:1,6:1\n! ==> Fatal error occurred, no output PDF file produced!\nTranscript written on texput.log.\n"
#You must select the correct size of the plot in advance
fig.set_size_inches(3.54,3.54)
plt.savefig("graph.pdf",
#This is simple recomendation for publication plots
dpi=1000,
# Plot will be occupy a maximum of available space
bbox_inches='tight',
)
# \InputIfFileExists{filename.pgf}{success text}{failure text}