From 4b501ca8eebaa1ee8bb01f7f7cdcd07bf4031041 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 1 Jul 2025 12:31:02 +0200 Subject: [PATCH] Autodetect dimension from units. This lets one write `ScaleBar(1, "kpc")` instead of the slightly redundant `ScaleBar(1, "kpc", "astro-length")`. Note that changes only occur in the constructor; "auto" is not when later calling set_dimension (directly or via the property) because that property's mutable semantics seem a bit fuzzy anyways: what happens if one sets the dimension to something incompatible with the units? I would believe `ScaleBar.dimension` should be a readonly property directly derived from `ScaleBar.units`. --- matplotlib_scalebar/scalebar.py | 12 ++++++++++-- tests/test_scalebar.py | 5 +++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/matplotlib_scalebar/scalebar.py b/matplotlib_scalebar/scalebar.py index efd5a5d..edfc28d 100644 --- a/matplotlib_scalebar/scalebar.py +++ b/matplotlib_scalebar/scalebar.py @@ -174,7 +174,7 @@ def __init__( self, dx, units="m", - dimension="si-length", + dimension="auto", label=None, length_fraction=None, height_fraction=None, @@ -230,6 +230,7 @@ def __init__( * ``:const:`pixel-length```: scale bar showing px, kpx, Mpx, etc. * ``:const:`angle```: scale bar showing \u00b0, \u2032 or \u2032\u2032. * a :class:`matplotlib_scalebar.dimension._Dimension` object + * ``:const:`auto``` (the default): autodetect dimension based on *units* :type dimension: :class:`str` or :class:`matplotlib_scalebar.dimension._Dimension` @@ -355,7 +356,14 @@ def __init__( raise ValueError("loc and location are specified and not equal") self.dx = dx - self.dimension = dimension # Should be initialize before units + if dimension == "auto": + for cls in _DIMENSION_LOOKUP.values(): + dimension = cls() + if dimension.is_valid_units(units): + break + else: + raise ValueError(f"Invalid unit ({units})") + self.dimension = dimension # Should be initialized before units self.units = units self.label = label self.length_fraction = length_fraction diff --git a/tests/test_scalebar.py b/tests/test_scalebar.py index 1093296..6336ead 100644 --- a/tests/test_scalebar.py +++ b/tests/test_scalebar.py @@ -398,3 +398,8 @@ def test_info(): plt.close() del fig + + +def test_auto_dimension(): + assert ScaleBar(1, "kpc").dimension.base_units == "pc" + assert ScaleBar(1, "1/um").dimension.base_units == "1/m"