Skip to content

Commit 3427e1f

Browse files
committed
refactor ptable_heatmap()'s tick_fmt() and add test for cbar_precision kwarg
1 parent ed171ec commit 3427e1f

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

pymatviz/ptable.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -302,12 +302,10 @@ def ptable_heatmap(
302302
def tick_fmt(val: float, _pos: int) -> str:
303303
# val: value at color axis tick (e.g. 10.0, 20.0, ...)
304304
# pos: zero-based tick counter (e.g. 0, 1, 2, ...)
305-
if heat_mode == "percent":
306-
# display color bar values as percentages
307-
return f"{val:.0%}"
308-
if val < 1e4:
309-
return f"{val:{cbar_precision or precision or '.0f'}}"
310-
return f"{val:{cbar_precision or precision or '.2g'}}"
305+
default = (
306+
".0%" if heat_mode == "percent" else (".0f" if val < 1e4 else ".2g")
307+
)
308+
return f"{val:{cbar_precision or precision or default}}"
311309

312310
cbar = fig.colorbar(
313311
mappable, cax=cb_ax, orientation="horizontal", format=tick_fmt

tests/test_ptable.py

+9
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,15 @@ def test_ptable_heatmap(
149149
with pytest.raises(ValueError, match=r"Unexpected symbol\(s\) foobar"):
150150
ptable_heatmap(glass_elem_counts, exclude_elements=["foobar"])
151151

152+
# test cbar_precision
153+
ax = ptable_heatmap(glass_elem_counts, cbar_precision=".3f")
154+
cbar_1st_label = ax.child_axes[0].get_xticklabels()[0].get_text()
155+
assert cbar_1st_label == "0.000"
156+
157+
ax = ptable_heatmap(glass_elem_counts, heat_mode="percent", cbar_precision=".3%")
158+
cbar_1st_label = ax.child_axes[0].get_xticklabels()[0].get_text()
159+
assert cbar_1st_label == "0.000%"
160+
152161

153162
def test_ptable_heatmap_ratio(
154163
steel_formulas: list[str],

0 commit comments

Comments
 (0)