Skip to content

Commit

Permalink
Merge pull request #385 from flying-sheep/context
Browse files Browse the repository at this point in the history
Add ConTeXt support
  • Loading branch information
nschloe committed Feb 5, 2020
2 parents 22b7a5c + 4d1c787 commit d9f636f
Show file tree
Hide file tree
Showing 31 changed files with 189 additions and 74 deletions.
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- run: sudo apt update
# <https://stackoverflow.com/a/44333806/353337>
- run: DEBIAN_FRONTEND=noninteractive sudo apt install tzdata
- run: sudo apt install -y texlive-latex-base texlive-latex-extra
- run: sudo apt install -y texlive-latex-base texlive-latex-extra context
- run: pip3 install -U pytest pytest-cov excode --user
- checkout
- run: excode README.md test/zzz_readme_test.py --filter python,test
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
python-version: "3.x"
- uses: actions/checkout@v1
- name: Install dependencies
run: sudo apt-get install -y texlive-latex-base texlive-latex-extra python3-tk python3-scipy
run: sudo apt-get install -y texlive-latex-base texlive-latex-extra context python3-tk python3-scipy
- name: Install package
run: |
pip install --upgrade pip
Expand Down
34 changes: 27 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ figures like

![](https://nschloe.github.io/tikzplotlib/example.png)

for native inclusion into LaTeX documents.
for native inclusion into LaTeX or ConTeXt documents.

The output of tikzplotlib is in
[PGFPlots](http://pgfplots.sourceforge.net/pgfplots.pdf), a LaTeX library that sits on
[PGFPlots](http://pgfplots.sourceforge.net/pgfplots.pdf), a TeX library that sits on
top of [PGF/TikZ](https://en.wikipedia.org/wiki/PGF/TikZ) and describes graphs in terms
of axes, data etc. Consequently, the output of tikzplotlib

Expand Down Expand Up @@ -95,7 +95,7 @@ table {%
```
(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 LaTeX work flow.
Tweaking the plot is straightforward and can be done as part of your TeX work flow.
[The fantastic PGFPlots manual](http://pgfplots.sourceforge.net/pgfplots.pdf) contains
great examples of how to make your plot look even better.

Expand All @@ -120,10 +120,12 @@ to install/update.
```python
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 LaTeX source code. A convenient way of
3. Add the contents of `mytikz.tex` into your TeX source code. A convenient way of
doing so is via
```latex
\input{/path/to/mytikz.tex}
Expand All @@ -132,11 +134,29 @@ to install/update.
included in the header of your document:
```latex
\usepackage[utf8]{inputenc}
\usepackage{fontspec} % optional
\usepackage{pgfplots}
\DeclareUnicodeCharacter{2212}{−}
\usepgfplotslibrary{groupplots,dateplot}
\usetikzlibrary{patterns,shapes.arrows}
\pgfplotsset{compat=newest}
\usepgfplotslibrary{groupplots}
\usepgfplotslibrary{dateplot}
```
or:
```latex
\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:
```python
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.
Expand Down
31 changes: 19 additions & 12 deletions test/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,14 @@ def _unidiff_output(expected, actual):


def assert_equality(
plot, filename, assert_compilation=True, **extra_get_tikz_code_args
plot, filename, assert_compilation=True, flavor="latex", **extra_get_tikz_code_args
):
plot()
code = tikzplotlib.get_tikz_code(
include_disclaimer=False, float_format=".8g", **extra_get_tikz_code_args
include_disclaimer=False,
float_format=".8g",
flavor=flavor,
**extra_get_tikz_code_args,
)
plt.close()

Expand All @@ -47,13 +50,16 @@ def assert_equality(
if assert_compilation:
plot()
code = tikzplotlib.get_tikz_code(
include_disclaimer=False, standalone=True, **extra_get_tikz_code_args
include_disclaimer=False,
standalone=True,
flavor=flavor,
**extra_get_tikz_code_args,
)
plt.close()
assert _compile(code) is not None, code
assert _compile(code, flavor) is not None, code


def _compile(code):
def _compile(code, flavor):
_, tmp_base = tempfile.mkstemp()

tex_file = tmp_base + ".tex"
Expand All @@ -64,13 +70,14 @@ def _compile(code):
os.chdir(os.path.dirname(tex_file))

# compile the output to pdf
cmdline = dict(
latex=["pdflatex", "--interaction=nonstopmode"],
context=["context", "--nonstopmode"],
)[flavor]
try:
subprocess.check_output(
["pdflatex", "--interaction=nonstopmode", tex_file],
stderr=subprocess.STDOUT,
)
subprocess.check_output(cmdline + [tex_file], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print("pdflatex output:")
print(f"{cmdline[0]} output:")
print("=" * 70)
print(e.output.decode("utf-8"))
print("=" * 70)
Expand All @@ -81,15 +88,15 @@ def _compile(code):
return output_pdf


def compare_mpl_latex(plot):
def compare_mpl_tex(plot, flavor="latex"):
plot()
code = tikzplotlib.get_tikz_code(standalone=True)
directory = os.getcwd()
filename = "test-0.png"
plt.savefig(filename)
plt.close()

pdf_file = _compile(code)
pdf_file = _compile(code, flavor)
pdf_dirname = os.path.dirname(pdf_file)

# Convert PDF to PNG.
Expand Down
2 changes: 1 addition & 1 deletion test/test_annotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_arrows.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,5 +70,5 @@ def to_texstring(s):
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_axvline.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_barchart_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_basic_sin.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_colorbars.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,5 +81,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
20 changes: 20 additions & 0 deletions test/test_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from helpers import assert_equality


def plot():
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

x, y = np.meshgrid(np.linspace(0, 1), np.linspace(0, 1))
z = x ** 2 - y ** 2

fig = plt.figure()
plt.pcolormesh(x, y, z, cmap=cm.viridis)

return fig


def test():
assert_equality(plot, __file__[:-3] + "_reference.tex", flavor="context")
return
16 changes: 16 additions & 0 deletions test/test_context_reference.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
\starttikzpicture

\startaxis[
tick align=outside,
tick pos=left,
x grid style={white!69.019608!black},
xmin=0, xmax=1,
xtick style={color=black},
y grid style={white!69.019608!black},
ymin=0, ymax=1,
ytick style={color=black}
]
\addplot graphics [includegraphics cmd=\pgfimage,xmin=0, xmax=1, ymin=0, ymax=1] {tmp-000.png};
\stopaxis

\stoptikzpicture
2 changes: 1 addition & 1 deletion test/test_contourf.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_datetime_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
2 changes: 1 addition & 1 deletion test/test_errorband.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_fancybox.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,5 +204,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_hatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,4 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
2 changes: 1 addition & 1 deletion test/test_legend3.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ def plot():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_legend_best_location.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_legend_line_scatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_line_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_line_dashes.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_pandas_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_patch_styles.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_scatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
# helpers.print_tree(plot())
2 changes: 1 addition & 1 deletion test/test_steps.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ def test():
if __name__ == "__main__":
import helpers

helpers.compare_mpl_latex(plot)
helpers.compare_mpl_tex(plot)
3 changes: 2 additions & 1 deletion tikzplotlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
__status__,
__version__,
)
from ._save import get_tikz_code, save
from ._cleanfigure import clean_figure
from ._save import Flavors, get_tikz_code, save

__all__ = [
"__author__",
Expand All @@ -21,4 +21,5 @@
"get_tikz_code",
"save",
"clean_figure",
"Flavors",
]
8 changes: 4 additions & 4 deletions tikzplotlib/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def __init__(self, data, obj): # noqa: C901
if self.is_subplot:
self.content.append("\n\\nextgroupplot")
else:
self.content.append("\\begin{axis}")
self.content.append(data["flavor"].start("axis"))

def get_begin_code(self):
content = self.content
Expand All @@ -158,10 +158,10 @@ def get_begin_code(self):

def get_end_code(self, data):
if not self.is_subplot:
return "\\end{axis}\n\n"
return data["flavor"].end("axis") + "\n\n"
elif self.is_subplot and self.nsubplots == self.subplot_index:
data["is_in_groupplot_env"] = False
return "\\end{groupplot}\n\n"
return data["flavor"].end("groupplot") + "\n\n"

return ""

Expand Down Expand Up @@ -419,7 +419,7 @@ def _subplot(self, obj, data):
group_style.extend(data["extra groupstyle options [base]"])
options = ["group style={{{}}}".format(", ".join(group_style))]
self.content.append(
"\\begin{{groupplot}}[{}]".format(", ".join(options))
data["flavor"].start("groupplot") + f"[{', '.join(options)}]"
)
data["is_in_groupplot_env"] = True
data["pgfplots libs"].add("groupplots")
Expand Down

0 comments on commit d9f636f

Please sign in to comment.