Skip to content

Commit

Permalink
Merge pull request #63 from nschloe/fix-integer-test
Browse files Browse the repository at this point in the history
Fix integer test
  • Loading branch information
nschloe authored Jun 4, 2021
2 parents 760c9fb + 0787da1 commit 3703c1e
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 64 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ build/
.pytest_cache/
venv/
.idea/
.tox/
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ publish: tag upload

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

lint:
black --check .
Expand Down
5 changes: 3 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
[metadata]
name = termplotlib
version = 0.3.4
version = 0.3.5
author = Nico Schlömer
author_email = [email protected]
description = Plotting on the command line
description = Python plotting for the command line
url = https://github.com/nschloe/termplotlib
project_urls =
Code=https://github.com/nschloe/termplotlib
Expand Down Expand Up @@ -39,6 +39,7 @@ package_dir =
packages = find:
install_requires =
importlib_metadata;python_version<"3.8"
numpy
python_requires = >=3.6

[options.packages.find]
Expand Down
22 changes: 15 additions & 7 deletions src/termplotlib/barh.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import List
from typing import List, Optional

import numpy as np

from .helpers import is_unicode_standard_output

Expand All @@ -13,7 +15,12 @@ def _trim_trailing_zeros(lst):


def barh(
vals, labels=None, max_width=40, bar_width=1, show_vals=True, force_ascii=False
vals: List[int],
labels: Optional[List[str]] = None,
max_width: int = 40,
bar_width: int = 1,
show_vals: bool = True,
force_ascii: bool = False,
):
matrix = _get_matrix_of_eighths(vals, max_width, bar_width)

Expand All @@ -24,13 +31,14 @@ def barh(

fmt = []
if labels is not None:
cfmt = "{{:{}s}}".format(max([len(str(label)) for label in labels]))
max_len = max(len(str(label)) for label in labels)
cfmt = f"{{:{max_len}s}}"
fmt.append(cfmt)

if show_vals:
all_int = all(val == int(val) for val in vals)
if all_int:
cfmt = "{{:{}d}}".format(max([len(str(val)) for val in vals]))
if np.issubdtype(np.asarray(vals).dtype, np.integer):
max_len = max(len(str(val)) for val in vals)
cfmt = f"{{:{max_len}d}}"
else:
cfmt = "{}"
fmt.append("[" + cfmt + "]")
Expand All @@ -54,7 +62,7 @@ def barh(
return out


def _get_matrix_of_eighths(counts, max_size, bar_width) -> List[List[int]]:
def _get_matrix_of_eighths(counts, max_size: int, bar_width: int) -> List[List[int]]:
"""
Returns a matrix of integers between 0-8 encoding bar lengths in histogram.
Expand Down
4 changes: 3 additions & 1 deletion src/termplotlib/figure.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Optional

from .barh import barh
from .helpers import create_padding_tuple
from .hist import hist
Expand All @@ -9,7 +11,7 @@ def figure(*args, **kwargs):


class Figure:
def __init__(self, width=None, padding=0):
def __init__(self, width: Optional[int] = None, padding: int = 0):
self._content = []
self._width = width
self._subfigures = None
Expand Down
3 changes: 2 additions & 1 deletion src/termplotlib/helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import sys
from typing import List, Tuple, Union


def create_padding_tuple(padding):
def create_padding_tuple(padding: Union[int, List[int], Tuple[int, int]]):
# self._padding is a 4-tuple: top, right, bottom, left (just like CSS)
if isinstance(padding, int):
out = (padding, padding, padding, padding)
Expand Down
53 changes: 25 additions & 28 deletions src/termplotlib/hist.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
from typing import List, Optional

from .barh import _get_matrix_of_eighths, _trim_trailing_zeros, barh
from .helpers import is_unicode_standard_output


def hist(
counts,
bin_edges,
orientation="vertical",
max_width=40,
bins=20,
counts: List[int],
bin_edges: List[float],
orientation: str = "vertical",
max_width: int = 40,
grid=None,
bar_width=1,
strip=False,
force_ascii=False,
bar_width: int = 1,
strip: bool = False,
force_ascii: bool = False,
):
if orientation == "vertical":
return hist_vertical(
Expand All @@ -26,26 +27,24 @@ def hist(
return hist_horizontal(
counts,
bin_edges,
max_width=40,
bins=20,
max_width=max_width,
bar_width=bar_width,
force_ascii=force_ascii,
)


def hist_horizontal(
counts,
bin_edges,
max_width=40,
bins=20,
bar_width=1,
show_bin_edges=True,
show_counts=True,
force_ascii=False,
counts: List[int],
bin_edges: List[float],
max_width: int = 40,
bar_width: int = 1,
show_bin_edges: bool = True,
show_counts: bool = True,
force_ascii: bool = False,
):
if show_bin_edges:
labels = [
"{:+.2e} - {:+.2e}".format(bin_edges[k], bin_edges[k + 1])
f"{bin_edges[k]:+.2e} - {bin_edges[k+1]:+.2e}"
for k in range(len(bin_edges) - 1)
]
else:
Expand All @@ -59,24 +58,22 @@ def hist_horizontal(
show_vals=show_counts,
force_ascii=force_ascii,
)

return out


def _flip(matrix):
def _flip(matrix: List[List[int]]) -> List[List[int]]:
"""Mirrors a matrix left to right"""
n_cols = len(matrix[0])
return [[row[-(col_i + 1)] for row in matrix] for col_i in range(n_cols)]


def hist_vertical(
counts,
bins=30,
max_height=10,
bar_width=2,
strip=False,
xgrid=None,
force_ascii=False,
counts: List[int],
max_height: int = 10,
bar_width: int = 2,
strip: bool = False,
xgrid: Optional[List[int]] = None,
force_ascii: bool = False,
):
if xgrid is None:
xgrid = []
Expand Down
31 changes: 16 additions & 15 deletions src/termplotlib/plot.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import subprocess
from typing import List, Optional, Tuple


def plot(
x,
y,
width=80,
height=25,
label=None,
xlim=None,
ylim=None,
xlabel=None,
title=None,
extra_gnuplot_arguments=None,
plot_command="plot '-' w lines",
ticks_scale=0,
x: List[float],
y: List[float],
width: int = 80,
height: int = 25,
label: Optional[str] = None,
xlim: Optional[Tuple[float, float]] = None,
ylim: Optional[Tuple[float, float]] = None,
xlabel: Optional[str] = None,
title: Optional[str] = None,
extra_gnuplot_arguments: Optional[List[str]] = None,
plot_command: str = "plot '-' w lines",
ticks_scale: int = 0,
):
p = subprocess.Popen(
["gnuplot"],
Expand All @@ -29,10 +30,10 @@ def plot(
gnuplot_input.append(f"set tics scale {ticks_scale}")

if xlim:
gnuplot_input.append("set xrange [{}:{}]".format(xlim[0], xlim[1]))
gnuplot_input.append(f"set xrange [{xlim[0]}:{xlim[1]}]")

if ylim:
gnuplot_input.append("set yrange [{}:{}]".format(ylim[0], ylim[1]))
gnuplot_input.append(f"set yrange [{ylim[0]}:{ylim[1]}]")

if xlabel:
gnuplot_input.append(f'set xlabel "{xlabel}"')
Expand Down Expand Up @@ -60,5 +61,5 @@ def plot(
return _remove_empty_lines(out.decode())


def _remove_empty_lines(string):
def _remove_empty_lines(string: str):
return string.split("\n")[1:-2]
18 changes: 9 additions & 9 deletions src/termplotlib/subplot.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import List, Optional, Tuple, Union

from .figure import Figure


Expand All @@ -9,10 +11,10 @@ class SubplotGrid:
def __init__(
self,
layout,
width=None,
column_widths=None,
border_style="thin",
padding=(1, 2),
width: Optional[int] = None,
column_widths: Optional[List[int]] = None,
border_style: str = "thin",
padding: Union[int, List[int], Tuple[int, int]] = (1, 2),
):
assert (
len(layout) == 2
Expand Down Expand Up @@ -72,11 +74,9 @@ def get_string(self):
]
column_widths = [
max(
[
len(line)
for i in range(self._layout[0])
for line in cstrings[i][j].split("\n")
]
len(line)
for i in range(self._layout[0])
for line in cstrings[i][j].split("\n")
)
for j in range(self._layout[1])
]
Expand Down
2 changes: 2 additions & 0 deletions tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ def test_plot_lim():
)
string = fig.get_string()

# for some reason, this gives a different result locally; perhaps a different
# gnuplotlib version
ref = """ header
1 +---------------------------------------+
Expand Down

0 comments on commit 3703c1e

Please sign in to comment.