Matplot2tikz
Save matplotlib figures as TikZ/PGFplots for smooth integration into LaTeX.
Install / Use
/learn @ErwindeGelder/Matplot2tikzREADME
matplot2tikz
The artist formerly known as <em>tikzplotlib</em>.
This is matplot2tikz, a Python tool for converting matplotlib figures into PGFPlots (PGF/TikZ) figures like

for native inclusion into LaTeX or ConTeXt documents.
The output of matplot2tikz is in PGFPlots, a TeX library that sits on top of PGF/TikZ and describes graphs in terms of axes, data etc. Consequently, the output of matplot2tikz
- retains more information,
- can be more easily understood, and
- is more easily editable
than raw TikZ output. For example, the matplotlib figure
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("ggplot")
t = np.arange(0.0, 2.0, 0.1)
s = np.sin(2 * np.pi * t)
s2 = np.cos(2 * np.pi * t)
plt.plot(t, s, "o-", lw=4.1)
plt.plot(t, s2, "o-", lw=4.1)
plt.xlabel("time (s)")
plt.ylabel("Voltage (mV)")
plt.title("Simple plot $\\frac{\\alpha}{2}$")
plt.grid(True)
import matplot2tikz
matplot2tikz.save("test.tex")
--> (see above) gives
\begin{tikzpicture}
\definecolor{chocolate2267451}{RGB}{226,74,51}
\definecolor{dimgray85}{RGB}{85,85,85}
\definecolor{gainsboro229}{RGB}{229,229,229}
\definecolor{steelblue52138189}{RGB}{52,138,189}
\begin{axis}[
axis background/.style={fill=gainsboro229},
axis line style={white},
tick align=outside,
tick pos=left,
title={Simple plot \(\displaystyle \frac{\alpha}{2}\)},
x grid style={white},
xlabel=\textcolor{dimgray85}{time (s)},
xmajorgrids,
xmin=-0.095, xmax=1.995,
xtick style={color=dimgray85},
y grid style={white},
ylabel=\textcolor{dimgray85}{Voltage (mV)},
ymajorgrids,
ymin=-1.1, ymax=1.1,
ytick style={color=dimgray85}
]
\addplot [line width=1.64pt, chocolate2267451, mark=*, mark size=3, mark options={solid}]
table {%
0 0
% [...]
1.9 -0.587785252292473
};
\addplot [line width=1.64pt, steelblue52138189, mark=*, mark size=3, mark options={solid}]
table {%
0 1
% [...]
1.9 0.809016994374947
};
\end{axis}
\end{tikzpicture}
(Use get_tikz_code() instead of save() if you want the code as a string.)
Tweaking the plot is straightforward and can be done as part of your TeX work flow. The fantastic PGFPlots manual contains great examples of how to make your plot look even better.
Of course, not all figures produced by matplotlib can be converted without error. Notably, 3D plots don't work.
Installation
matplot2tikz is available from the Python Package Index, so simply do
pip install matplot2tikz
to install.
Usage
-
Generate your matplotlib plot as usual.
-
Instead of
pyplot.show(), invoke matplot2tikz byimport matplot2tikz matplot2tikz.save("mytikz.tex") # or matplot2tikz.save("mytikz.tex", flavor="context")to store the TikZ file as
mytikz.tex. -
Add the contents of
mytikz.texinto your TeX source code. A convenient way of doing so is via\input{/path/to/mytikz}Also make sure that the packages for PGFPlots and proper Unicode support and are included in the header of your document:
\usepackage[utf8]{inputenc} \usepackage{pgfplots} \DeclareUnicodeCharacter{2212}{−} \usepgfplotslibrary{groupplots,dateplot} \usetikzlibrary{patterns,shapes.arrows} \pgfplotsset{compat=newest}or:
\setupcolors[state=start] \usemodule[tikz] \usemodule[pgfplots] \usepgfplotslibrary[groupplots,dateplot] \usetikzlibrary[patterns,shapes.arrows] \pgfplotsset{compat=newest} \unexpanded\def\startgroupplot{\groupplot} \unexpanded\def\stopgroupplot{\endgroupplot}You can also get the code via:
import matplot2tikz matplot2tikz.Flavors.latex.preamble() # or matplot2tikz.Flavors.context.preamble() -
[Optional] Clean up the figure before exporting to tikz using the
clean_figurecommand.import matplotlib.pyplot as plt import numpy as np # ... do your plotting import matplot2tikz matplot2tikz.clean_figure() matplot2tikz.save("test.tex")The command will remove points that are outside the axes limits, simplify curves and reduce point density for the specified target resolution.
matplot2tikz vs. tikzplotlib
This matplot2tikz library originated from the tikzplotlib project. The reason a new library has been created is because tikzplotlib is no longer maintained and maintainance could only be done by the single owner of the tikzplotlib library. If you need to use third-party code that already depends on tikzplotlib, it is suggested to change the tikzplotlib dependency to matplot2tikz. If this is not possible, a workaround is to put the following code before importing the third-party code:
import sys
import matplot2tikz
sys.modules["tikzplotlib"] = matplot2tikz
# Do other imports, e.g., using `import my_third_party_library`
# If tikzplotlib is used in this library, it will automatically use matplot2tikz instead.
If you are updating your own scripts from tikzplotlib, you can simply use an import alias:
import matplot2tikz as tikzplotlib
Contributing
If you experience bugs, would like to contribute, have nice examples of what matplot2tikz can do, or if you are just looking for more information, then please visit matplot2tikz's GitHub page.
For contributing, follow these steps:
- Download the git repository, e.g., using
git clone git@github.com:ErwindeGelder/matplot2tikz.git. - Create a virtual environment, e.g., using
python -m venv venv. - Activate the virtual environment (e.g., on Windows,
venv\Scripts\activate). - Install
uvusingpip install uvand thentox-uvusinguv pip install tox-uv. - The main branch is protected, meaning that you cannot directly push changes to this branch.
