Skip to content

Commit

Permalink
Merge pull request #72 from nschloe/barh-same-float-formatting
Browse files Browse the repository at this point in the history
barh same float formatting
  • Loading branch information
nschloe authored Sep 23, 2021
2 parents ce31fd9 + ef16d2b commit 5763ef0
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = termplotlib
version = 0.3.8
version = 0.3.9
author = Nico Schlömer
author_email = nico.schloemer@gmail.com
description = Python plotting for the command line
Expand Down
14 changes: 13 additions & 1 deletion src/termplotlib/barh.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import decimal
from typing import List, Optional

import numpy as np
Expand All @@ -12,6 +13,7 @@ def barh(
max_width: int = 40,
bar_width: int = 1,
show_vals: bool = True,
val_format: Optional[str] = None,
force_ascii: bool = False,
):
partition = _get_partition(vals, max_width)
Expand All @@ -29,7 +31,17 @@ def barh(
fmt.append(cfmt)

if show_vals:
if np.issubdtype(np.asarray(vals).dtype, np.integer):
if val_format is not None:
cfmt = val_format
elif np.issubdtype(np.asarray(vals).dtype, float):
# find max decimal length
# https://stackoverflow.com/a/6190291/353337
num_digits = max(
-decimal.Decimal(str(val)).as_tuple().exponent for val in vals
)
max_len = max(len(str(val)) for val in vals)
cfmt = f"{{:.{num_digits}f}}"
elif np.issubdtype(np.asarray(vals).dtype, np.integer):
max_len = max(len(str(val)) for val in vals)
cfmt = f"{{:{max_len}d}}"
else:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_barh.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ def test_barh_floats():
)


def test_barh_floats_different_precision():
fig = tpl.figure()
fig.barh([3, 2.5341234], ["Cats", "Dogs"])
# fig.show()
string = fig.get_string()

ref = """\
Cats [3.0000000] ████████████████████████████████████████
Dogs [2.5341234] █████████████████████████████████▊"""

assert string == ref, "\n" + string


def test_div_by_zero():
fig = tpl.figure()
fig.barh([0, 0], ["Eggs", "Dogs"])
Expand Down

0 comments on commit 5763ef0

Please # to comment.