• Stars
    star
    2,398
  • Rank 19,121 (Top 0.4 %)
  • Language
    Python
  • License
    MIT License
  • Created almost 15 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ“Š Save matplotlib figures as TikZ/PGFplots for smooth integration into LaTeX.

tikzplotlib

The artist formerly known as matplotlib2tikz.

PyPi Version Packaging status PyPI pyversions DOI GitHub stars Downloads

Documentation Status awesome

gh-actions codecov LGTM Code style: black

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

for native inclusion into LaTeX or ConTeXt documents.

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

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

tikzplotlib.save("test.tex")
import matplotlib as mpl

plt.close()
mpl.rcParams.update(mpl.rcParamsDefault)

--> (see above) gives

\begin{tikzpicture}

\definecolor{color0}{rgb}{0.886274509803922,0.290196078431373,0.2}
\definecolor{color1}{rgb}{0.203921568627451,0.541176470588235,0.741176470588235}

\begin{axis}[
axis background/.style={fill=white!89.8039215686275!black},
axis line style={white},
tick align=outside,
tick pos=left,
title={Simple plot \(\displaystyle \frac{\alpha}{2}\)},
x grid style={white},
xlabel={time (s)},
xmajorgrids,
xmin=-0.095, xmax=1.995,
xtick style={color=white!33.3333333333333!black},
y grid style={white},
ylabel={Voltage (mV)},
ymajorgrids,
ymin=-1.1, ymax=1.1,
ytick style={color=white!33.3333333333333!black}
]
\addplot [line width=1.64pt, color0, mark=*, mark size=3, mark options={solid}]
table {%
0 0
0.1 0.587785252292473
% [...]
1.9 -0.587785252292473
};
\addplot [line width=1.64pt, color1, mark=*, mark size=3, mark options={solid}]
table {%
0 1
0.1 0.809016994374947
% [...]
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

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

pip install tikzplotlib

to install.

Usage

  1. Generate your matplotlib plot as usual.

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

    import tikzplotlib
    
    tikzplotlib.save("mytikz.tex")
    # or
    tikzplotlib.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.tex}

    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 tikzplotlib
    
    tikzplotlib.Flavors.latex.preamble()
    # or
    tikzplotlib.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 tikzplotlib
    
    tikzplotlib.clean_figure()
    tikzplotlib.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.

    The feature originated from the matlab2tikz project and is adapted to matplotlib.

Contributing

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

Testing

tikzplotlib has automatic unit testing to make sure that the software doesn't accidentally get worse over time. In test/, a number of test cases are specified. Those run through tikzplotlib and compare the output with a previously stored reference TeX file.

To run the tests, just check out this repository and type

pytest

License

tikzplotlib is published under the MIT license.

More Repositories

1

meshio

๐Ÿ•ธ๏ธ input/output for many mesh formats
Python
1,930
star
2

tiptop

๐Ÿ–ฅ๏ธ Command-line system monitoring
Python
1,749
star
3

tuna

๐ŸŸ Python profile viewer
Python
1,363
star
4

perfplot

๐Ÿ“ˆ Performance analysis for Python snippets
Python
1,339
star
5

awesome-scientific-computing

๐Ÿ˜Ž Curated list of awesome software for numerical analysis and scientific computing
Python
1,319
star
6

pygmsh

๐Ÿ•ธ๏ธ Gmsh for Python
Python
844
star
7

matplotx

๐Ÿ“Š More styles and useful extensions for Matplotlib
Python
789
star
8

termplotlib

๐Ÿ“ˆ Plotting on the command line
Python
669
star
9

colorio

๐ŸŒˆ Tools for color research
TeX
320
star
10

stressberry

Stress tests for the Raspberry Pi ๐Ÿ˜…
Python
319
star
11

github-trends

๐Ÿ“ˆ GitHub star history plots
260
star
12

dufte

๐Ÿ“ˆ Minimalistic Matplotlib style
Python
216
star
13

deadlink

๐Ÿ’€ Checks and fixes URLs in code and documentation.
Python
162
star
14

cplot

๐ŸŒˆ Plot complex functions
Python
149
star
15

termtables

๐Ÿ–ฅ๏ธ Pretty tables in the terminal
Python
98
star
16

pytest-codeblocks

๐Ÿ“„ Test code blocks in your READMEs
Python
95
star
17

xhub

Extend GitHub pages with math, graphs etc.
JavaScript
91
star
18

action-cached-lfs-checkout

GitHub checkout action with LFS files pulled from cache
Just
90
star
19

ua-beamer

A LaTeX beamer theme for the University of Antwerp
TeX
75
star
20

pipdate

Small pip update helpers.
Python
73
star
21

matlab-guidelines

Guidelines for writing clean and fast code in MATLAB
TeX
67
star
22

spectro

๐ŸŽต Audio file analysis
Python
47
star
23

tablign

Aligns columns in your ASCII tables on the command line or in vim.
Python
43
star
24

pyfoobar

Python project template/scaffold and best practices
Python
41
star
25

betterspy

๐Ÿ‘€ Visualization for SciPy sparse matrices.
Python
40
star
26

color-data

๐ŸŒˆ Collected experimental data for color research
Python
39
star
27

stackoverflow-trends

๐Ÿ“ˆ StackOverflow trends
35
star
28

maelstrom

Numerical simulation of magnetohydrodynamics.
Python
33
star
29

purple-pi

๐Ÿ’œ LaTeX math wherever you want
JavaScript
31
star
30

stackoverflow-card

JavaScript
31
star
31

markdown-math-acid-test

Showcase GitHub math bugs
25
star
32

fontman

Manage and update your installed fonts.
Python
21
star
33

tau

The better pi
Python
20
star
34

pyfma

Fused multiply-add (with a single rounding) for Python.
Python
20
star
35

scipyx

SciPy fixes and extensions
Python
18
star
36

gitfaces

Fetch contributor avatars for a GitHub repository
Python
17
star
37

epicycler

Create epicycle animations.
Python
15
star
38

fjson

Python JSON writer with formatted floats
Python
14
star
39

python-vs-cpp

C++
13
star
40

identinum

Identify exact expression for decimal.
Python
9
star
41

mikado

Friendly solver interfaces for Trilinos.
C++
8
star
42

materials

Density, magnetic permeability etc. for a range of materials.
Python
8
star
43

note-on-cam16

Algorithmic improvements for the CIECAM02 and CAM16 color appearence models
TeX
8
star
44

matheon-html5-template

Matheon HTML5 presentation template
JavaScript
8
star
45

flow

Navier-Stokes and heat equation with FEniCS.
Python
5
star
46

nosh

A numerical solver for nonlinear Schrรถdinger equations
C++
4
star
47

tex-font-errors-cheatsheet

Cheat sheet(s) for decoding the meaning of TeX font errors
3
star
48

rhino

Python
3
star
49

vandermonde

๐Ÿ“ Tools for working with Vandermonde matrices, e.g., Bjรถrck-Pereyra.
Python
3
star
50

keygen_licensing_tools

Tools for license valididation with Keygen.sh
Python
3
star
51

corona-charts

Corona data and charts, updated automatically
Python
2
star
52

plm

Python
2
star
53

math-test

2
star
54

github-mathml-test

2
star
55

parabolic

Time stepping methods for parabolic problems.
Python
2
star
56

sippp

Fortran library for the solution of singularly perturbed parabolic problems
Fortran
2
star
57

nschloe.github.io

HTML
2
star
58

hanoi-material

Class material for nonlinear optimization at Hanoi Autumn School 2013
MATLAB
2
star
59

talk-python-scientific

Python in Scientific Computation
JavaScript
2
star
60

trilinos-tutorial

C++
1
star
61

tspsolve

Solution algorithms for the travelling salesman problem.
Python
1
star
62

launchpadtools

Tools for submitting packages to Ubuntu Launchpad
Python
1
star
63

nschloe

about me
1
star