Install tikzplotlib via pip
mainInstall the tikzplotlib package from the Python Package Index using pip.
pip install tikzplotlibrepository·main·Indexed 25 days ago
https://github.com/nschloe/tikzplotlibA Python tool that converts matplotlib figures into PGFPlots/TikZ code for inclusion in LaTeX or ConTeXt documents. It allows users to retain data structures like axes and data points rather than exporting raw images. Key features include the save() and get_tikz_code() functions, support for different TeX flavors, and a clean_figure() utility to optimize output by simplifying curves and pruning points. Note that 3D plots cannot be converted and will result in errors.
Install the tikzplotlib package from the Python Package Index using pip.
pip install tikzplotlibOnce you have generated a .tex file, include it in your LaTeX source using \input{}.
Required LaTeX Preamble Configuration:
Ensure your document header includes pgfplots and proper Unicode support:
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
\DeclareUnicodeCharacter{2212}{−}
\usepgfplotslibrary{groupplots,dateplot}
\usetikzlibrary{patterns,shapes.arrows}
\pgfplotsset{compat=newest}The Axes class is responsible for converting a Matplotlib Axes object into PGFPlots code. It extracts various properties from the Matplotlib object, including:
xmin, xmax, ymin, ymax), axis inversion (x dir=reverse), and logarithmic scaling (xmode=log, ymode=log) including the log base.tick align=outside, tick align=center, or tick align=inside).xmajorgrids, xminorgrids, etc.) and their styles.axis x line=top).groupplots logic.Note: Axes that host a colorbar are treated implicitly by the associated axis and are skipped by the Axes class to avoid duplication.
When using tikzplotlib, Matplotlib hatches are mapped to TikZ patterns. Note that tikzplotlib currently has limitations regarding hatch density and complex hatch strings.
Supported single-character hatches and their TikZ equivalents:
-: horizontal lines|: vertical lines/: north east lines\: north west lines+: gridx: crosshatch.: crosshatch dots*: fivepointed starso: sixpointed starsO: bricksLimitations:
// to increase density), tikzplotlib will only use the first character and issue a warning. Only single-character hatches are fully supported.o and O are noted as having poor PGF counterparts.\usetikzlibrary{patterns}, which tikzplotlib attempts to add automatically.tikzplotlib and will result in errors.You can specify the target TeX engine using the flavor argument in tikzplotlib.save().
flavor="latex" (default)flavor="context"You can also retrieve the required preamble for these flavors using tikzplotlib.Flavors.latex.preamble() or tikzplotlib.Flavors.context.preamble().
To convert a matplotlib figure to a .tex file, use tikzplotlib.save(filename). This creates a PGFPlots-based TeX file that can be included in LaTeX or ConTeXt documents.
If you need the TikZ code as a string instead of saving it to a file, use tikzplotlib.get_tikz_code().
import matplotlib.pyplot as plt
import numpy as np
import tikzplotlib
# ... create your plot ...
tikzplotlib.save("test.tex")Use tikzplotlib.clean_figure() before calling save() to optimize the output. This command removes points outside the axes limits, simplifies curves, and reduces point density for the target resolution. This is useful for reducing file size and complexity.
import matplotlib.pyplot as plt
import tikzplotlib
# ... do your plotting ...
tikzplotlib.clean_figure()
tikzplotlib.save("test.tex")The clean_figure() function also supports 3D lineplots (using mpl_toolkits.mplot3d). It will prune points outside the visible 3D bounding box and simplify the path to reduce the complexity of the exported TikZ code.
from tikzplotlib import get_tikz_code, cleanfigure
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z ** 2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.plot(x, y, z)
ax.set_xlim([-2, 2])
ax.set_ylim([-2, 2])
ax.set_zlim([-2, 2])
ax.view_init(30, 30)
raw = get_tikz_code(fig)
clean_figure(fig)
clean = get_tikz_code()
# Verify reduction in complexity
numLinesRaw = raw.count("\n")
numLinesClean = clean.count("\n")
assert numLinesRaw - numLinesClean == 14The draw_image function is an internal utility used by tikzplotlib to convert Matplotlib image objects (like those created by plt.imshow) into PGFPlots code. It handles saving the image data to a file (typically as a .png) and generating the corresponding LaTeX \addplot graphics command using \pgfimage to ensure compatibility.
When an image is processed:
data dictionary) and the POSIX-style file path.Use clean_figure() to prepare a Matplotlib figure for TikZ export. This function minimizes the number of data points required for the resulting TikZ figure by applying path simplification and pruning points outside the visible axis limits.
Warning: This is an impure function; it modifies the Matplotlib figure object directly.
fig (Matplotlib figure handle, optional): The figure to clean. If None or 'gcf', the current figure is used.target_resolution (int, list, or np.array, optional): The target resolution in PPI (Pixels Per Inch).np.array is provided, it is interpreted as [Height, Width].600.scale_precision (float, optional): A scalar value indicating precision when scaling down. Default is 1.0.from tikzplotlib import get_tikz_code, cleanfigure
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 100, 20)
y = np.linspace(1, 100, 20)
fig, ax = plt.subplots(1, 1, figsize=(5, 5))
ax.plot(x, y)
ax.set_ylim([20, 80])
ax.set_xlim([20, 80])
# Get raw TikZ code before cleaning
raw = get_tikz_code()
# Clean the figure (modifies fig in place)
clean_figure(fig)
# Get TikZ code after cleaning
clean = get_tikz_code()
# The clean version will have significantly fewer lines/points
print("Difference in lines:", raw.count("\n") - clean.count("\n"))save() function is the primary entrypoint for converting a Matplotlib figure into a TikZ/PGFPlots file. It allows you to specify the output path and the desired Flavors (e.g., TikZ or PGFPlots).