5

What are some good, well-maintained packages for converting matplotlib plots to Tikz files for inclusion in latex documents?

rhz
  • 193

2 Answers2

5

matplotlib supports to export to PGF (the graphics language behind TikZ) or to directly built the plot via LaTeX and save it as a PDF.

To use this just use the following in your Python code:

import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use("pgf")
# create your plot
plt.savefig("file.pgf") # save as PGF file which can be used in your document via `\input`
plt.savefig("file.pdf") # save as PDF created with LaTeX

You can customize the output of the PDF/PGF via mpl.rcParams.update(), which expects a dictionary as argument with which you can set several interesting parameters for the created PDF/PGF:

{
    "pgf.texsystem":   "pdflatex", # or any other engine you want to use
    "text.usetex":     True,       # use TeX for all texts
    "font.family":     "serif",
    "font.serif":      [],         # empty entries should cause the usage of the document fonts
    "font.sans-serif": [],
    "font.monospace":  [],
    "font.size":       10,         # control font sizes of different elements
    "axes.labelsize":  10,
    "legend.fontsize": 9,
    "xtick.labelsize": 9,
    "ytick.labelsize": 9,
    "pgf.preamble": [              # specify additional preamble calls for LaTeX's run
        r"\usepackage[T1]{fontenc}",
        r"\usepackage{siunitx}",
    ],
}
Skillmon
  • 60,462
  • I tried it, but the generated PGF file is huge (over 6 MB for a single picture) – Erel Segal-Halevi Feb 11 '24 at 15:08
  • @ErelSegal-Halevi then your data is huge, keep in mind that it stores every point on every curve. If that's the case for you, storing the data in a pixel based format can turn out to be smaller (so converting it to PNG, for instance). – Skillmon Feb 11 '24 at 18:05
4

tikzplotlib (formerly matplotlib2tikz) creates LaTeX code using the pgfplots package. It's available on Pypi, so it can be installed with pip.

Basically do

import tikzplotlib

and then

tikzplotlib.save('filename.tex')

after generating a figure. In your LaTeX-file add

\usepackage{pgfplots}

to the preamble, and

\input{filename}

to add the figure.

The tikzplotlib.save function has multiple options for modifying the code, so have a look at its docstring.

Skillmon
  • 60,462
Torbjørn T.
  • 206,688