diff --git a/.gitignore b/.gitignore index bf3055e..49a04be 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ build/ .pytest_cache/ venv/ .idea/ +.tox/ diff --git a/Makefile b/Makefile index 93f5520..3681ab9 100644 --- a/Makefile +++ b/Makefile @@ -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 . diff --git a/setup.cfg b/setup.cfg index 93c9daf..2025097 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,9 +1,9 @@ [metadata] name = termplotlib -version = 0.3.4 +version = 0.3.5 author = Nico Schlömer author_email = nico.schloemer@gmail.com -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 @@ -39,6 +39,7 @@ package_dir = packages = find: install_requires = importlib_metadata;python_version<"3.8" + numpy python_requires = >=3.6 [options.packages.find] diff --git a/src/termplotlib/barh.py b/src/termplotlib/barh.py index d137eb7..f7a7f89 100644 --- a/src/termplotlib/barh.py +++ b/src/termplotlib/barh.py @@ -1,4 +1,6 @@ -from typing import List +from typing import List, Optional + +import numpy as np from .helpers import is_unicode_standard_output @@ -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) @@ -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 + "]") @@ -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. diff --git a/src/termplotlib/figure.py b/src/termplotlib/figure.py index 73ef48f..731d578 100644 --- a/src/termplotlib/figure.py +++ b/src/termplotlib/figure.py @@ -1,3 +1,5 @@ +from typing import Optional + from .barh import barh from .helpers import create_padding_tuple from .hist import hist @@ -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 diff --git a/src/termplotlib/helpers.py b/src/termplotlib/helpers.py index 262ad3f..9b1df73 100644 --- a/src/termplotlib/helpers.py +++ b/src/termplotlib/helpers.py @@ -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) diff --git a/src/termplotlib/hist.py b/src/termplotlib/hist.py index d72aa92..2393815 100644 --- a/src/termplotlib/hist.py +++ b/src/termplotlib/hist.py @@ -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( @@ -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: @@ -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 = [] diff --git a/src/termplotlib/plot.py b/src/termplotlib/plot.py index 9704c6c..56768ca 100644 --- a/src/termplotlib/plot.py +++ b/src/termplotlib/plot.py @@ -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"], @@ -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}"') @@ -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] diff --git a/src/termplotlib/subplot.py b/src/termplotlib/subplot.py index 36125a0..812d78d 100644 --- a/src/termplotlib/subplot.py +++ b/src/termplotlib/subplot.py @@ -1,3 +1,5 @@ +from typing import List, Optional, Tuple, Union + from .figure import Figure @@ -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 @@ -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]) ] diff --git a/tests/test_plot.py b/tests/test_plot.py index 8584edc..0bad3d0 100644 --- a/tests/test_plot.py +++ b/tests/test_plot.py @@ -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 +---------------------------------------+