Skip to content

Commit

Permalink
Merge pull request #500 from nschloe/tables-fix-2
Browse files Browse the repository at this point in the history
external tables fix
  • Loading branch information
nschloe authored Aug 10, 2021
2 parents b27364c + a4f2e05 commit a48d84b
Show file tree
Hide file tree
Showing 80 changed files with 435 additions and 9,093 deletions.
28 changes: 14 additions & 14 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ name: ci
on:
push:
branches:
- main
- main
pull_request:
branches:
- main
- main

jobs:
lint:
Expand All @@ -25,15 +25,15 @@ jobs:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
steps:
- uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- uses: actions/checkout@v2
# - name: Install system dependencies
# run: sudo apt-get install -y texlive-latex-base texlive-latex-extra context python3-tk
- name: Test with tox
run: |
pip install tox
tox -- --cov tikzplotlib --cov-report xml --cov-report term
- uses: codecov/codecov-action@v1
if: ${{ matrix.python-version == '3.9' }}
- uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- uses: actions/checkout@v2
# - name: Install system dependencies
# run: sudo apt-get install -y texlive-latex-base texlive-latex-extra context python3-tk
- name: Test with tox
run: |
pip install tox
tox -- --cov tikzplotlib --cov-report xml --cov-report term
- uses: codecov/codecov-action@v1
if: ${{ matrix.python-version == '3.9' }}
33 changes: 0 additions & 33 deletions Makefile

This file was deleted.

37 changes: 26 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,13 @@ The output of tikzplotlib is in
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

* retains more information,
* can be more easily understood, and
* is more easily editable
- retains more information,
- can be more easily understood, and
- is more easily editable

than [raw TikZ output](https://matplotlib.org/users/whats_new.html#pgf-tikz-backend).
For example, the matplotlib figure

```python
import matplotlib.pyplot as plt
import numpy as np
Expand Down Expand Up @@ -67,6 +68,7 @@ mpl.rcParams.update(mpl.rcParamsDefault)
```
-->
(see above) gives

```latex
\begin{tikzpicture}
Expand Down Expand Up @@ -108,6 +110,7 @@ table {%
\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.
Expand All @@ -121,33 +124,39 @@ Notably, [3D plots don't work](https://github.com/matplotlib/matplotlib/issues/7

tikzplotlib is [available from the Python Package
Index](https://pypi.org/project/tikzplotlib/), so simply do

```
pip install tikzplotlib
```
to install.

to install.

### Usage

1. Generate your matplotlib plot as usual.

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

```python
import tikzplotlib

tikzplotlib.save("mytikz.tex")
# or
tikzplotlib.save("mytikz.tex", flavor="context")
```
to store the TikZ file as `mytikz.tex`.

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

```latex
\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:

Also make sure that the packages for PGFPlots and proper Unicode support and are
included in the header of your document:

```latex
\usepackage[utf8]{inputenc}
\usepackage{pgfplots}
Expand All @@ -156,7 +165,9 @@ to install.
\usetikzlibrary{patterns,shapes.arrows}
\pgfplotsset{compat=newest}
```
or:

or:

```latex
\setupcolors[state=start]
\usemodule[tikz]
Expand All @@ -167,7 +178,9 @@ to install.
\unexpanded\def\startgroupplot{\groupplot}
\unexpanded\def\stopgroupplot{\endgroupplot}
```
You can also get the code via:

You can also get the code via:

```python
import tikzplotlib

Expand All @@ -177,6 +190,7 @@ to install.
```

4. Optional: clean up the figure before exporting to tikz using the `clean_figure` command.

```python
import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -188,9 +202,10 @@ to install.
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](https://github.com/matlab2tikz/matlab2tikz) project and is adapted to
matplotlib.
Expand All @@ -201,7 +216,6 @@ 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](https://github.com/nschloe/tikzplotlib).


### Testing

tikzplotlib has automatic unit testing to make sure that the software doesn't
Expand All @@ -210,6 +224,7 @@ 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
```
Expand Down
31 changes: 31 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
version := `python3 -c "from configparser import ConfigParser; p = ConfigParser(); p.read('setup.cfg'); print(p['metadata']['version'])"`
name := `python3 -c "from configparser import ConfigParser; p = ConfigParser(); p.read('setup.cfg'); print(p['metadata']['name'])"`


default:
@echo "\"just publish\"?"

tag:
@if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi
curl -H "Authorization: token `cat ~/.github-access-token`" -d '{"tag_name": "{{version}}"}' https://api.github.com/repos/nschloe/{{name}}/releases

upload: clean
@if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi
# https://stackoverflow.com/a/58756491/353337
python3 -m build --sdist --wheel .
twine upload dist/*

publish: tag upload

clean:
@find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
@rm -rf src/*.egg-info/ build/ dist/ .tox/

format:
isort .
black .
blacken-docs README.md

lint:
black --check .
flake8 .
3 changes: 2 additions & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = tikzplotlib
version = 0.9.9
version = 0.9.10
author = Nico Schlömer
author_email = [email protected]
description = Convert matplotlib figures into TikZ/PGFPlots
Expand All @@ -15,6 +15,7 @@ license = MIT
license_file = LICENSE
classifiers =
Development Status :: 4 - Beta
Framework :: Matplotlib
License :: OSI Approved :: MIT License
Operating System :: OS Independent
Programming Language :: Python
Expand Down
6 changes: 3 additions & 3 deletions src/tikzplotlib/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,12 @@ def __init__(self, data, obj): # noqa: C901
if obj.get_xscale() == "log":
self.axis_options.append("xmode=log")
self.axis_options.append(
"log basis x={{{}}}".format(_try_f2i(obj.xaxis._scale.base))
f"log basis x={{{_try_f2i(obj.xaxis._scale.base)}}}"
)
if obj.get_yscale() == "log":
self.axis_options.append("ymode=log")
self.axis_options.append(
"log basis y={{{}}}".format(_try_f2i(obj.yaxis._scale.base))
f"log basis y={{{_try_f2i(obj.yaxis._scale.base)}}}"
)

# Possible values for get_axisbelow():
Expand Down Expand Up @@ -771,7 +771,7 @@ def _handle_listed_color_map(cmap, data):
reps = int(float(cmap.N) / len(cmap.colors) - 0.5) + 1
repeated_cols = reps * cmap.colors
colors = [
"rgb({k}{unit})=({rgb[0]:{ff}},{rgb[1]:{ff}},{rgb[2]:{ff}})"
f"rgb({k}{unit})=({rgb[0]:{ff}},{rgb[1]:{ff}},{rgb[2]:{ff}})"
for k, rgb in enumerate(repeated_cols[: cmap.N])
]
colormap_string = "{{mymap}}{{[1{}]\n {}\n}}".format(unit, ";\n ".join(colors))
Expand Down
2 changes: 1 addition & 1 deletion src/tikzplotlib/_cleanfigure.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ def _get_collection_data(collection):
if is3D:
# https://stackoverflow.com/questions/51716696/extracting-data-from-a-3d-scatter-plot-in-matplotlib
offsets = collection._offsets3d
xData, yData, zData = [o.data for o in offsets]
xData, yData, zData = (o.data for o in offsets)
data = _stack_data_3D(xData, yData, zData)
else:
offsets = collection.get_offsets()
Expand Down
14 changes: 7 additions & 7 deletions src/tikzplotlib/_hatches.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
r"""
Map matplotlib hatches to tikz patterns
Map matplotlib hatches to tikz patterns
For matplotlib hatches, see:
https://matplotlib.org/3.1.1/gallery/shapes_and_collections/hatch_demo.html
For matplotlib hatches, see:
https://matplotlib.org/3.1.1/gallery/shapes_and_collections/hatch_demo.html
For patterns in tikzpgf:
Ch 26 Pattern Lbrary in the manual
Requires \usetikzlibrary{patterns}
For patterns in tikzpgf:
Ch 26 Pattern Lbrary in the manual
Requires \usetikzlibrary{patterns}
"""

# These methods exist, and might be relevant (in the future?):
Expand Down Expand Up @@ -93,7 +93,7 @@ def _mpl_hatch2pgfp_pattern(data, hatch, color_name, color_rgba):
try:
pgfplots_pattern = _MP_HATCH2PGF_PATTERN[hatch]
except KeyError:
warnings.warn("tikzplotlib: The hatch", hatch, "is ignored.")
warnings.warn(f"tikzplotlib: The hatch {hatch} is ignored.")
return data, []

data["tikz libs"].add("patterns")
Expand Down
13 changes: 10 additions & 3 deletions src/tikzplotlib/_line2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,10 +266,16 @@ def _table(obj, data): # noqa: C901
if data["table_row_sep"] != "\n":
# don't want the \n in the table definition, just in the data (below)
opts.append("row sep=" + data["table_row_sep"].strip())

if data["externals search path"] is not None:
esp = data["externals search path"]
opts.append(f"search path={{{esp}}}")

if len(opts) > 0:
content.append("table [{}] {{%\n".format(",".join(opts)))
opts_str = ",".join(opts)
content.append(f"table [{opts_str}] {{")
else:
content.append("table {%\n")
content.append("table {")

plot_table = []
table_row_sep = data["table_row_sep"]
Expand All @@ -284,12 +290,13 @@ def _table(obj, data): # noqa: C901
plot_table.append(f"{x:{xformat}}{col_sep}{y:{ff}}{table_row_sep}")

if data["externalize tables"]:
filepath, rel_filepath = _files.new_filepath(data, "table", ".tsv")
filepath, rel_filepath = _files.new_filepath(data, "table", ".dat")
with open(filepath, "w") as f:
# No encoding handling required: plot_table is only ASCII
f.write("".join(plot_table))
content.append(str(rel_filepath))
else:
content.append("%\n")
content.extend(plot_table)

content.append("};\n")
Expand Down
Loading

0 comments on commit a48d84b

Please sign in to comment.