Skip to main content

Convert matplotlib figures into TikZ/PGFPlots

Project description

makintikz

The artist formerly known as tikzplotlib & matplot2tikz.

PyPI - Version GitHub License PyPI - Python Version Ruff Checked with mypy codecov PyPI Downloads

This is makintikz, a Python tool for converting matplotlib figures into PGFPlots (PGF/TikZ) figures like

for native inclusion into LaTeX or ConTeXt documents.

The output of makintikz 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 makintikz

  • 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 makintikz

makintikz.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

makintikz is available from the Python Package Index, so simply do

pip install makintikz

to install.

Usage

  1. Generate your matplotlib plot as usual.

  2. Instead of pyplot.show(), invoke makintikz by

    import makintikz
    
    makintikz.save("mytikz.tex")
    # or
    makintikz.save("mytikz.tex", flavor="context")
    

    to store the TikZ file as mytikz.tex.

  3. Add the contents of mytikz.tex into 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 makintikz
    
    makintikz.Flavors.latex.preamble()
    # or
    makintikz.Flavors.context.preamble()
    
  4. [Optional] Clean up the figure before exporting to tikz using the clean_figure command.

    import matplotlib.pyplot as plt
    import numpy as np
    
    # ... do your plotting
    
    import makintikz
    
    makintikz.clean_figure()
    makintikz.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.

makintikz vs. matplot2tikz vs. tikzplotlib

The matplot2tikz library and makintikz 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 makintikz. If this is not possible, a workaround is to put the following code before importing the third-party code:

import sys
import makintikz
sys.modules["tikzplotlib"] = makintikz
# Do other imports, e.g., using `import my_third_party_library`
# If tikzplotlib is used in this library, it will automatically use makintikz instead.

If you are updating your own scripts from tikzplotlib, you can simply use an import alias:

import makintikz as tikzplotlib

Contributing

If you experience bugs, would like to contribute, have nice examples of what makintikz can do, or if you are just looking for more information, then please visit makintikz's GitHub page.

For contributing, follow these steps:

  1. Download the git repository, e.g., using git clone git@github.com:AlexChrzanowski/makintikz.git.

  2. Create a virtual environment, e.g., using python -m venv venv.

  3. Activate the virtual environment (e.g., on Windows, venv\Scripts\activate).

  4. Install uv using pip install uv and then tox-uv using uv pip install tox-uv.

  5. The main branch is protected, meaning that you cannot directly push changes to this branch. Therefore, if you want to make changes, do so in a seperate branch. For example, you can create a new branch using git checkout -b feature/my_awesome_new_feature.

  6. Before pushing changes, ensure that the code adheres to the linting rules and that the tests are successful. Run tox. This does a linting check and runs all test scripts. To manually perform these steps, use the following commands:

    1. Run tox -e lint. You can do the linting commands manually using:
      1. (One time) uv pip install -r requirements-lint.txt
      2. ruff format . --check (remove the --check flag to let ruff do the formatting)
      3. ruff check .
      4. mypy .
    2. Run tox -e py310.
    3. Run tox -e py311.
    4. Run tox -e py312.
    5. Run tox -e py313.
    6. Run tox -e py314.
    7. Run tox -e combine-test-reports
  7. Check if the tests covered everything using the coverage report in /reports/coverage_html/index.html.

    NOTE: Currently, now all code is covered. Ideally, all code is covered, but for now, ensure that all new code is covered by the testing.

  8. Push changes to GitHub. If everything is OK and you want to merge your changes to the main branch, create a pull request. Ideally, there is at least one reviewer who reviews the pull request before the merge.

Note that currently only "Code owners" can merge pull requests onto the main branch. This is to ensure that not everyone can break the main code (even unintentially). If you want to be a "Code owner", let us know!

License

makintikz is published under the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

makintikz-1.0.0.tar.gz (179.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

makintikz-1.0.0-py3-none-any.whl (69.8 kB view details)

Uploaded Python 3

File details

Details for the file makintikz-1.0.0.tar.gz.

File metadata

  • Download URL: makintikz-1.0.0.tar.gz
  • Upload date:
  • Size: 179.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for makintikz-1.0.0.tar.gz
Algorithm Hash digest
SHA256 4b521cc8beb53f3ca90b920d9da96b59d0c798eeec10ad73bc60fb4c13d1d00a
MD5 86041c367e485f0f453649f30c50cace
BLAKE2b-256 261fa664e807e45d35167711bb59d31ec0a6e4cba950cda5aa421abc3d650ae2

See more details on using hashes here.

Provenance

The following attestation bundles were made for makintikz-1.0.0.tar.gz:

Publisher: publish-to-pypi.yaml on AlexChrzanowski/MakinTikZ

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file makintikz-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: makintikz-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 69.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for makintikz-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 44273264c1875b1871deb84e47e11e22e6e94d75e8f77f2da0cca0f2c30bc0d9
MD5 ec64110dede3ff262e5beb5ac0a9953c
BLAKE2b-256 8c9debf66d301e4c130c9af82d8f0e11019454af91d166b84c15cf1e67777e3e

See more details on using hashes here.

Provenance

The following attestation bundles were made for makintikz-1.0.0-py3-none-any.whl:

Publisher: publish-to-pypi.yaml on AlexChrzanowski/MakinTikZ

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page