From 77b1a5c967f49b6549fcc7806664a6f08d29791d Mon Sep 17 00:00:00 2001 From: maclariz Date: Mon, 16 Nov 2026 12:01:22 +0000 Subject: [PATCH 1/6] Honour full ScalebarConfig in orientation and cluster maps plot_orientation_map and plot_cluster_map read only sampling, units, length and color from a scalebar dict, ignored every other field, and failed on a ScalebarConfig or True. A user dict also replaced the scan calibration entirely, so the bar fell back to pixels. Resolve the scalebar through _resolve_scalebar so every ScalebarConfig field is honoured, and have the OrientationMap wrappers fill only the missing sampling and units from the scan calibration via _fill_scalebar_calibration. Bar width and padding left at the ScalebarConfig defaults still scale with the map size. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfYfoAEq86paxTeAox --- src/quantem/diffraction/orientation.py | 18 +++- .../diffraction/orientation_visualization.py | 82 ++++++++++++------- 2 files changed, 67 insertions(+), 33 deletions(-) diff --git a/src/quantem/diffraction/orientation.py b/src/quantem/diffraction/orientation.py index ab000c81..b2d77aa4 100644 --- a/src/quantem/diffraction/orientation.py +++ b/src/quantem/diffraction/orientation.py @@ -2731,6 +2731,20 @@ def scan_scalebar(self) -> dict | None: md = self.metadata.get("peaks", {}) or {} return scan_scalebar(md) + def _scalebar_with_calibration(self, scalebar): + """Fill a requested scale bar's sampling and units from the scan. + + A dict, ScalebarConfig or True that does not set its own sampling + and units takes them from :attr:`scan_scalebar`. The default (True) + draws no bar when the scan was never calibrated, as before. + """ + from quantem.core.visualization.visualization_utils import _fill_scalebar_calibration + + cal = self.scan_scalebar + if cal is None: + return None if scalebar is True else scalebar + return _fill_scalebar_calibration(scalebar, cal["sampling"], cal["units"]) + def plot_orientation(self, direction: str = "z", match: int = 0, **kwargs): """IPF-colored orientation map with the color wedge beside it. @@ -2755,7 +2769,7 @@ def plot_orientation(self, direction: str = "z", match: int = 0, **kwargs): """ from quantem.diffraction.orientation_visualization import plot_orientation_map - kwargs.setdefault("scalebar", self.scan_scalebar) + kwargs["scalebar"] = self._scalebar_with_calibration(kwargs.get("scalebar", True)) return plot_orientation_map( self, direction=direction, match=match, **self._default_mask(kwargs) ) @@ -2803,7 +2817,7 @@ def plot_cluster_map(self, clusters: dict, **kwargs): """ from quantem.diffraction.orientation_visualization import plot_cluster_map - kwargs.setdefault("scalebar", self.scan_scalebar) + kwargs["scalebar"] = self._scalebar_with_calibration(kwargs.get("scalebar", True)) return plot_cluster_map(self, clusters, **kwargs) def plot_cluster_pole_figure(self, clusters: dict, pole=(0, 0, 1), **kwargs): diff --git a/src/quantem/diffraction/orientation_visualization.py b/src/quantem/diffraction/orientation_visualization.py index 4534f134..758443cc 100644 --- a/src/quantem/diffraction/orientation_visualization.py +++ b/src/quantem/diffraction/orientation_visualization.py @@ -6,7 +6,11 @@ import torch from quantem.core.utils.rotations import quat_to_matrix -from quantem.core.visualization.visualization_utils import add_scalebar_to_ax +from quantem.core.visualization.visualization_utils import ( + ScalebarConfig, + _resolve_scalebar, + add_scalebar_to_ax, +) from quantem.diffraction.crystal import Crystal # one color per candidate phase, used consistently across every plot; index @@ -361,12 +365,48 @@ def wedge_legend( ax.axis("off") + +def _draw_map_scalebar(ax, scalebar, shape) -> None: + """Draw a scale bar on a scan map from any form `scalebar` may take. + + Accepts None/False (no bar), True, a dict of :class:`ScalebarConfig` + fields, a ScalebarConfig or a ``ShowParams.Scalebar``. Every field is + honored. A bar width and padding left at the ScalebarConfig defaults are + scaled to the map size instead, since one pixel is invisible on a scan. + """ + cfg = _resolve_scalebar(scalebar) + if cfg is None: + return + defaults = ScalebarConfig() + width_px = shape[0] / 40 if cfg.width_px == defaults.width_px else cfg.width_px + pad_px = shape[0] / 80 if cfg.pad_px == defaults.pad_px else cfg.pad_px + add_scalebar_to_ax( + ax, + array_size=shape[1], + sampling=cfg.sampling, + length_units=cfg.length, + units=cfg.units, + width_px=width_px, + pad_px=pad_px, + color=cfg.color, + loc=cfg.loc, + fontsize=cfg.fontsize, + bold=cfg.bold, + box=cfg.box, + box_color=cfg.box_color, + box_alpha=cfg.box_alpha, + outline_color=cfg.outline_color, + outline_width=cfg.outline_width, + display_units=cfg.display_units, + ) + + def plot_orientation_map( om, direction: str = "z", match: int = 0, mask: np.ndarray | None = None, - scalebar: dict | None = None, + scalebar=None, figax=None, legend: bool = True, axsize: tuple[float, float] = (9.0, 4.5), @@ -427,8 +467,9 @@ def plot_orientation_map( Colorfulness relative to the corner colors: 1 keeps them exact, lower washes the map toward white. The legend is drawn with the same values. - scalebar : dict | None - Real-space scale bar, e.g. {"sampling": 30, "units": "A"}. + scalebar : bool | dict | ScalebarConfig | None + Real-space scale bar: True, a ScalebarConfig, or a dict of its + fields, e.g. {"sampling": 30, "units": "A", "loc": "lower left"}. crop : (r0, r1, c0, c1) | None Show only this window of the map (rows r0:r1, columns c0:c1). title : str | None @@ -501,18 +542,7 @@ def plot_orientation_map( ax.set_title(f"{om.crystal.name} in-plane orientation ({direction:g}\u00b0)") else: ax.set_title(f"{om.crystal.name} in-plane orientation") - if scalebar is not None: - add_scalebar_to_ax( - ax, - array_size=rgb.shape[1], - sampling=scalebar.get("sampling", 1.0), - length_units=scalebar.get("length", None), - units=scalebar.get("units", "pixels"), - width_px=rgb.shape[0] / 40, - pad_px=rgb.shape[0] / 80, - color=scalebar.get("color", "white"), - loc="lower right", - ) + _draw_map_scalebar(ax, scalebar, rgb.shape) if legend and ax_leg is not None: wedge_legend( om.crystal, @@ -855,7 +885,7 @@ def plot_cluster_map( om, clusters: dict, colors: np.ndarray | None = None, - scalebar: dict | None = None, + scalebar=None, figax=None, ): """Map of orientation clusters (variants), one color per cluster. @@ -870,8 +900,9 @@ def plot_cluster_map( Output of :meth:`OrientationMap.cluster_orientations`. colors : sequence | None One color per cluster, cycled; defaults to `CLUSTER_COLORS`. - scalebar : dict | None - Real-space scale bar, e.g. {"sampling": 30, "units": "A"}. + scalebar : bool | dict | ScalebarConfig | None + Real-space scale bar: True, a ScalebarConfig, or a dict of its + fields, e.g. {"sampling": 30, "units": "A", "loc": "lower left"}. figax : (fig, ax) | None Existing axes to draw into. @@ -910,18 +941,7 @@ def plot_cluster_map( for k in range(K) ] ax.legend(handles=handles, loc="center left", bbox_to_anchor=(1.01, 0.5), fontsize=8) - if scalebar is not None: - add_scalebar_to_ax( - ax, - array_size=rgb.shape[1], - sampling=scalebar.get("sampling", 1.0), - length_units=scalebar.get("length", None), - units=scalebar.get("units", "pixels"), - width_px=rgb.shape[0] / 40, - pad_px=rgb.shape[0] / 80, - color=scalebar.get("color", "white"), - loc="lower right", - ) + _draw_map_scalebar(ax, scalebar, rgb.shape) return fig, ax From 690c7262bcca2bdb961257a1a2d7dc8df3863b3c Mon Sep 17 00:00:00 2001 From: maclariz Date: Mon, 16 Nov 2026 12:23:29 +0000 Subject: [PATCH 2/6] Keep scan calibration when a scale bar sets display_units A scale bar passed to plot_phase, plot_dynamical or plot_correlation still replaced the scan calibration outright, so a config such as {"display_units": "nm"} arrived with units "pixels" and failed with "Cannot convert scale bar units 'pixels' to 'nm'". PhaseMap.plot_phase also read only four fields of the config. Add with_scan_calibration(), which fills sampling and units from the scan unless the scale bar sets its own, and use it for every scan-map plot: OrientationMap.plot_orientation and plot_cluster_map, CrystalMap.plot_dynamical and plot_correlation, and PhaseMap.plot_phase, which now also draws through _draw_map_scalebar so every ScalebarConfig field is honoured. On an uncalibrated scan, asking for display_units now raises an error that says the calibration is missing and how to set it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfYfoAEq86paxTeAox --- src/quantem/diffraction/crystal_map.py | 20 ++++-- src/quantem/diffraction/orientation.py | 67 ++++++++++++++++--- .../diffraction/orientation_visualization.py | 1 - src/quantem/diffraction/phase.py | 38 +++++------ 4 files changed, 88 insertions(+), 38 deletions(-) diff --git a/src/quantem/diffraction/crystal_map.py b/src/quantem/diffraction/crystal_map.py index acd98923..1d863893 100644 --- a/src/quantem/diffraction/crystal_map.py +++ b/src/quantem/diffraction/crystal_map.py @@ -537,7 +537,9 @@ def plot_dynamical(self, phase=None, strain: bool = False, crop: bool = True, ** if crop and m.any(): rows, cols = np.nonzero(m) sl = (slice(rows.min(), rows.max() + 1), slice(cols.min(), cols.max() + 1)) - kwargs.setdefault("scalebar", self.orientation_maps[0].scan_scalebar) + kwargs["scalebar"] = self.orientation_maps[0]._scalebar_with_calibration( + kwargs.get("scalebar", True) + ) if strain: comps = {k: v.numpy()[sl] for k, v in maps["strain"].items()} return bloch.plot_strain_crystal_frame(comps, mask=m[sl], **kwargs) @@ -750,9 +752,8 @@ def plot_phase(self, **kwargs): positions without moving a real boundary. phase_colors : np.ndarray, optional One RGB color per crystal. - scalebar : dict, "auto" or None, default="auto" - Real-space scale bar; "auto" takes the scan step carried by the - peaks. + scalebar : "auto", bool, dict, ScalebarConfig or None, default="auto" + Real-space scale bar; see :meth:`PhaseMap.plot_phase`. **kwargs Further arguments of :meth:`PhaseMap.plot_phase`. @@ -1220,9 +1221,14 @@ def plot_correlation(self, **kwargs): [f"{n} reliability" for n in self.names], ], ) - sb = self.orientation_maps[0].scan_scalebar - if sb is not None: - kwargs.setdefault("scalebar", [[sb] + [False] * (len(corr) - 1), [False] * len(corr)]) + # one bar, on the first panel; a nested list is taken as given + sb = kwargs.get("scalebar", True) + if not isinstance(sb, (list, tuple)): + sb = self.orientation_maps[0]._scalebar_with_calibration(sb) + if sb is None: + kwargs.pop("scalebar", None) + else: + kwargs["scalebar"] = [[sb] + [False] * (len(corr) - 1), [False] * len(corr)] return show_2d([corr, rel], **kwargs) def _phase_indices(self, phase) -> list[int]: diff --git a/src/quantem/diffraction/orientation.py b/src/quantem/diffraction/orientation.py index b2d77aa4..35dbedd2 100644 --- a/src/quantem/diffraction/orientation.py +++ b/src/quantem/diffraction/orientation.py @@ -114,6 +114,62 @@ def scan_scalebar(metadata: dict) -> dict | None: return {"sampling": step, "units": units} +def with_scan_calibration(scalebar, calibration: dict | None): + """Fill a requested scale bar's sampling and units from the scan. + + Parameters + ---------- + scalebar : bool | "auto" | dict | ScalebarConfig | None + The scale bar asked for. True and "auto" mean the scan calibration + as it stands; a dict or ScalebarConfig that does not set its own + sampling and units takes them from `calibration`. None or False + draws no bar. + calibration : dict | None + :func:`scan_scalebar` of the scan, or None when it was never + calibrated. + + Returns + ------- + bool | dict | ScalebarConfig | None + A scale bar any quantem plot accepts, or None for no bar. + + Raises + ------ + ValueError + If `scalebar` is an unknown string, or asks for `display_units` + while neither it nor the scan has a length calibration. + """ + from quantem.core.visualization.visualization_utils import ( + _fill_scalebar_calibration, + _parse_length_units, + _resolve_scalebar, + ) + + if isinstance(scalebar, str): + if scalebar != "auto": + raise ValueError( + f"scalebar must be 'auto', True, a dict or a ScalebarConfig, got {scalebar!r}" + ) + scalebar = True + if calibration is not None: + return _fill_scalebar_calibration(scalebar, calibration["sampling"], calibration["units"]) + if scalebar is True: + return None + cfg = _resolve_scalebar(scalebar) + if ( + cfg is not None + and cfg.display_units is not None + and _parse_length_units(cfg.units) is None + ): + raise ValueError( + f"display_units={cfg.display_units!r} needs a length calibration, but this " + "scan has none (its scale is in pixels). Set dataset.sampling and " + "dataset.units before detecting the Bragg disks, or give 'sampling' and " + "'units' in the scale bar." + ) + return scalebar + + def smooth_quaternions( quats: torch.Tensor, active: torch.Tensor, @@ -2735,15 +2791,10 @@ def _scalebar_with_calibration(self, scalebar): """Fill a requested scale bar's sampling and units from the scan. A dict, ScalebarConfig or True that does not set its own sampling - and units takes them from :attr:`scan_scalebar`. The default (True) - draws no bar when the scan was never calibrated, as before. + and units takes them from :attr:`scan_scalebar`; see + :func:`with_scan_calibration`. """ - from quantem.core.visualization.visualization_utils import _fill_scalebar_calibration - - cal = self.scan_scalebar - if cal is None: - return None if scalebar is True else scalebar - return _fill_scalebar_calibration(scalebar, cal["sampling"], cal["units"]) + return with_scan_calibration(scalebar, self.scan_scalebar) def plot_orientation(self, direction: str = "z", match: int = 0, **kwargs): """IPF-colored orientation map with the color wedge beside it. diff --git a/src/quantem/diffraction/orientation_visualization.py b/src/quantem/diffraction/orientation_visualization.py index 758443cc..b3271858 100644 --- a/src/quantem/diffraction/orientation_visualization.py +++ b/src/quantem/diffraction/orientation_visualization.py @@ -365,7 +365,6 @@ def wedge_legend( ax.axis("off") - def _draw_map_scalebar(ax, scalebar, shape) -> None: """Draw a scale bar on a scan map from any form `scalebar` may take. diff --git a/src/quantem/diffraction/phase.py b/src/quantem/diffraction/phase.py index 1e33796f..a4974a6b 100644 --- a/src/quantem/diffraction/phase.py +++ b/src/quantem/diffraction/phase.py @@ -512,7 +512,7 @@ def plot_phase( shade_gamma: float = 1.0, majority_filter: int = 0, reliability_range: tuple[float, float] | None = None, - scalebar: dict | str | None = "auto", + scalebar="auto", figax=None, ): """Dominant-phase map: color gives the crystal, brightness the evidence. @@ -553,11 +553,13 @@ def plot_phase( reliability_range : tuple | None Backwards-compatible shortcut: setting it selects ``shade_by="reliability"`` with this range. - scalebar : dict | "auto" | None - Real-space scale bar. "auto" (the default) takes the scan step - and units carried from the dataset by the orientation maps; a - dict such as {"sampling": 30, "units": "A"} overrides it, and - None draws no bar. + scalebar : "auto" | bool | dict | ScalebarConfig | None + Real-space scale bar. "auto" (the default) or True takes the + scan step and units carried from the dataset by the orientation + maps. A dict of ScalebarConfig fields or a ScalebarConfig + changes any of them, e.g. {"display_units": "nm", "loc": "lower + left"}, and keeps the scan calibration unless it sets its own + sampling and units. None or False draws no bar. figax : (fig, ax) | None Existing axes to draw into. @@ -571,12 +573,15 @@ def plot_phase( ValueError If `shade_by` is unknown or `shade_gamma` is not positive. """ - if isinstance(scalebar, str): - scalebar = self.orientation_maps[0].scan_scalebar if scalebar == "auto" else None import matplotlib.pyplot as plt - from quantem.core.visualization.visualization_utils import add_scalebar_to_ax - from quantem.diffraction.orientation_visualization import phase_color_cycle + from quantem.diffraction.orientation import with_scan_calibration + from quantem.diffraction.orientation_visualization import ( + _draw_map_scalebar, + phase_color_cycle, + ) + + scalebar = with_scan_calibration(scalebar, self.orientation_maps[0].scan_scalebar) assert self.phase_index is not None and self.reliability is not None phase_colors = phase_color_cycle(len(self.names), phase_colors) @@ -627,18 +632,7 @@ def plot_phase( ax.imshow(rgb, interpolation="nearest") ax.set_xticks([]) ax.set_yticks([]) - if scalebar is not None: - add_scalebar_to_ax( - ax, - array_size=rgb.shape[1], - sampling=scalebar.get("sampling", 1.0), - length_units=scalebar.get("length", None), - units=scalebar.get("units", "pixels"), - width_px=rgb.shape[0] / 40, - pad_px=rgb.shape[0] / 80, - color=scalebar.get("color", "white"), - loc="lower right", - ) + _draw_map_scalebar(ax, scalebar, rgb.shape) handles = [ plt.Line2D([0], [0], marker="s", ls="", color=c, label=n) for c, n in zip(phase_colors, self.names) From 30a63d1b3e70aab4a0f814aa4ed95ba964680694 Mon Sep 17 00:00:00 2001 From: maclariz Date: Mon, 16 Nov 2026 14:07:46 +0000 Subject: [PATCH 3/6] Warn when a scale bar has no calibration instead of failing Asking for display_units on an uncalibrated image (a plain array, or a scan never given a step size) raised "Cannot convert scale bar units 'pixels' to 'nm'", and asking show_2d for a scale bar on a plain array silently drew it in pixels. - add_scalebar_to_ax: display_units on a bar whose units are not a length now warns and draws the bar unconverted; a real-space to reciprocal mismatch still raises. - show_2d: a scale bar requested for a plain array without sampling and units warns that it is drawn in pixels and says how to calibrate it. - with_scan_calibration: on an uncalibrated scan, warns and drops display_units instead of raising. - Dataset3d.show passes its calibration to show_2d, which receives the frames as plain arrays and so would otherwise warn and lose it. Warnings are attributed to the first frame outside quantem, so they appear at each call site in a notebook instead of only once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfYfoAEq86paxTeAox --- src/quantem/core/datastructures/dataset3d.py | 9 ++- .../core/visualization/visualization.py | 35 ++++++++ .../core/visualization/visualization_utils.py | 80 +++++++++++++++++-- src/quantem/diffraction/orientation.py | 36 +++++---- 4 files changed, 137 insertions(+), 23 deletions(-) diff --git a/src/quantem/core/datastructures/dataset3d.py b/src/quantem/core/datastructures/dataset3d.py index 2e841c79..a4af93ef 100644 --- a/src/quantem/core/datastructures/dataset3d.py +++ b/src/quantem/core/datastructures/dataset3d.py @@ -10,7 +10,10 @@ from quantem.core.utils.validators import ensure_valid_array from quantem.core.visualization import show_2d from quantem.core.visualization.custom_normalizations import NormalizationConfig -from quantem.core.visualization.visualization_utils import ScalebarConfig +from quantem.core.visualization.visualization_utils import ( + ScalebarConfig, + _fill_scalebar_calibration, +) # show_2d keywords that set the normalization; same_scale leaves them alone _NORM_KEYS = ("norm", *(f.name for f in fields(NormalizationConfig))) @@ -348,6 +351,10 @@ def show( ): vmin, vmax = np.nanquantile(np.stack(images[:n_frames]), [0.02, 0.98]) kwargs["vmin"], kwargs["vmax"] = float(vmin), float(vmax) + # the frames go to show_2d as plain arrays, so carry the calibration + scalebar = _fill_scalebar_calibration( + scalebar, float(self.sampling[-1]), str(self.units[-1]) + ) fig, axes = show_2d(image_grid, scalebar=scalebar, title=label_grid, **kwargs) if pad_count > 0: for ax in np.array(axes).flat[-pad_count:]: diff --git a/src/quantem/core/visualization/visualization.py b/src/quantem/core/visualization/visualization.py index e1fc2a18..8c3b965c 100644 --- a/src/quantem/core/visualization/visualization.py +++ b/src/quantem/core/visualization/visualization.py @@ -25,6 +25,9 @@ ScalebarConfig, _fill_scalebar_calibration, _resolve_scalebar, + _scalebar_display_units, + _scalebar_lacks_calibration, + _warn_from_caller, add_arg_cbar_to_ax, add_cbar_to_ax, add_scalebar_to_ax, @@ -335,6 +338,26 @@ def calib(obj: Any) -> tuple[float, str] | None: return [[calib(a) for a in row] for row in arrays] +_UNCALIBRATED_SCALEBAR_WARNING = ( + "A scale bar was requested for a plain array, which carries no calibration, so it " + "is drawn in pixels. Pass the calibrated dataset (e.g. a Dataset2d) rather than its " + "array, or give 'sampling' and 'units' in the scale bar." +) + + +def _check_uncalibrated_scalebar(scalebar: Any, calibration: Any) -> bool: + """Whether a panel's scale bar falls back to pixels with no warning of its own. + + A bar asking for display_units is left to :func:`add_scalebar_to_ax`, + which warns that the conversion was skipped. + """ + return ( + calibration is None + and _scalebar_lacks_calibration(scalebar) + and _scalebar_display_units(scalebar) is None + ) + + def _normalize_show_input_to_grid( arrays: Any, # NDArray | Sequence[NDArray] | Sequence[Sequence[NDArray]] ) -> list[list[NDArray]]: @@ -615,6 +638,8 @@ def show_2d( scalebar = scalebar[0] if not isinstance(scalebar[0], Sequence) else scalebar[0][0] if calibrations[0][0] is not None: scalebar = _fill_scalebar_calibration(scalebar, *calibrations[0][0]) + elif _check_uncalibrated_scalebar(scalebar, None): + _warn_from_caller(_UNCALIBRATED_SCALEBAR_WARNING) if isinstance(title, Sequence) and not isinstance(title, str): # flatten title title = title[0] if isinstance(title[0], str) else title[0][0] @@ -651,6 +676,16 @@ def show_2d( figsize = kwargs.pop("figsize", (axsize[0] * ncols, axsize[1] * nrows)) fig, axs = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False) + if any( + _check_uncalibrated_scalebar( + normalized_args[i][j]["scalebar"], + calibrations[i][j] if i < len(calibrations) and j < len(calibrations[i]) else None, + ) + for i, row in enumerate(grid) + for j in range(len(row)) + ): + _warn_from_caller(_UNCALIBRATED_SCALEBAR_WARNING) + for i, row in enumerate(grid): for j, array in enumerate(row): figax_local = (fig, axs[i][j]) diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 21637605..fb6f1212 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -1,3 +1,6 @@ +import os +import sys +import warnings from dataclasses import dataclass from typing import Any, cast @@ -256,6 +259,64 @@ def _fill_scalebar_calibration(cfg: Any, sampling: float, units: str) -> Any: return resolved +_QUANTEM_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +def _warn_from_caller(message: str) -> None: + """Issue a UserWarning attributed to the first frame outside quantem. + + Python shows a warning once per source line, so a warning raised inside + quantem would appear only the first time. Attributing it to the caller's + line shows it for every call site in a script or notebook. + """ + if sys.version_info >= (3, 12): + warnings.warn(message, UserWarning, skip_file_prefixes=(_QUANTEM_ROOT + os.sep,)) + else: + # stacklevel counts from this function; step past every quantem frame + level, frame = 2, sys._getframe(1) + while frame is not None and frame.f_code.co_filename.startswith(_QUANTEM_ROOT + os.sep): + frame, level = frame.f_back, level + 1 + warnings.warn(message, UserWarning, stacklevel=level) + + +def _is_pixel_units(units: Any) -> bool: + """True for the uncalibrated scale bar units ("pixels", "pixel", "px").""" + return isinstance(units, str) and units.strip().lower() in ("pixels", "pixel", "px") + + +def _scalebar_lacks_calibration(cfg: Any) -> bool: + """Whether a requested scale bar carries no sampling and units of its own. + + Parameters + ---------- + cfg : None, bool, dict, ScalebarConfig or ShowParams.Scalebar + The scale bar as passed by the user. + + Returns + ------- + bool + False when no bar is requested. For a dict, True unless it gives both + "sampling" and "units". For anything else, True when its units are + still pixels. + """ + if cfg is None or cfg is False: + return False + if isinstance(cfg, dict): + return not ("sampling" in cfg and "units" in cfg) + resolved = _resolve_scalebar(cfg) + return resolved is not None and _is_pixel_units(resolved.units) + + +def _scalebar_display_units(cfg: Any) -> str | None: + """The display_units a scale bar asks for, or None.""" + if cfg is None or cfg is False or cfg is True: + return None + if isinstance(cfg, dict): + return cfg.get("display_units") + resolved = _resolve_scalebar(cfg) + return None if resolved is None else resolved.display_units + + def estimate_scalebar_length(length: float, sampling: float) -> tuple[float, float]: """Estimate an appropriate scale bar length based on data dimensions. @@ -310,9 +371,7 @@ def estimate_scalebar_length(length: float, sampling: float) -> tuple[float, flo # Accepted spellings (compared in lower case) for each unit above. _LENGTH_UNIT_ALIASES = { **dict.fromkeys(["pm", "picometer", "picometre", "picometers", "picometres"], "pm"), - **dict.fromkeys( - ["a", "å", "Å", "ang", "angstrom", "angstroms", "ångström", "ångströms"], "Å" - ), + **dict.fromkeys(["a", "å", "Å", "ang", "angstrom", "angstroms", "ångström", "ångströms"], "Å"), **dict.fromkeys(["nm", "nanometer", "nanometre", "nanometers", "nanometres"], "nm"), **dict.fromkeys( [ @@ -393,8 +452,7 @@ def _length_unit_factor(from_units: str, to_units: str) -> float: if src[1] != dst[1]: kinds = {1: "a real-space length", -1: "a reciprocal length"} raise ValueError( - f"Cannot convert {from_units!r} ({kinds[src[1]]}) to {to_units!r} " - f"({kinds[dst[1]]})." + f"Cannot convert {from_units!r} ({kinds[src[1]]}) to {to_units!r} ({kinds[dst[1]]})." ) ratio = _LENGTH_UNITS_IN_ANGSTROM[src[0]] / _LENGTH_UNITS_IN_ANGSTROM[dst[0]] return ratio if src[1] == 1 else 1 / ratio @@ -501,6 +559,14 @@ def add_scalebar_to_ax( """ from matplotlib.font_manager import FontProperties + if display_units is not None and _parse_length_units(units) is None: + _warn_from_caller( + f"display_units={display_units!r} ignored: the scale bar is in {units!r}, " + "which is not a calibrated length, so it is drawn without conversion. Pass a " + "calibrated dataset rather than its array, or give 'sampling' and 'units' in " + "the scale bar." + ) + display_units = None if display_units is not None: if isinstance(sampling, (tuple, list)): sampling = np.asarray(sampling, dtype=float) @@ -546,9 +612,7 @@ def add_scalebar_to_ax( if box: bar.patch.set(facecolor=box_color, edgecolor="none", alpha=box_alpha) if outline_color is not None: - effects = [ - patheffects.withStroke(linewidth=outline_width, foreground=outline_color) - ] + effects = [patheffects.withStroke(linewidth=outline_width, foreground=outline_color)] for artist in bar.size_bar.get_children(): artist.set_path_effects(effects) for artist in bar.txt_label.get_children(): diff --git a/src/quantem/diffraction/orientation.py b/src/quantem/diffraction/orientation.py index 35dbedd2..8740338f 100644 --- a/src/quantem/diffraction/orientation.py +++ b/src/quantem/diffraction/orientation.py @@ -136,13 +136,23 @@ def with_scan_calibration(scalebar, calibration: dict | None): Raises ------ ValueError - If `scalebar` is an unknown string, or asks for `display_units` - while neither it nor the scan has a length calibration. + If `scalebar` is an unknown string. + + Warns + ----- + UserWarning + When a scale bar is asked for on an uncalibrated scan without its own + sampling and units: it is drawn in pixels, and any `display_units` + is dropped. """ + from dataclasses import replace + from quantem.core.visualization.visualization_utils import ( _fill_scalebar_calibration, - _parse_length_units, _resolve_scalebar, + _scalebar_display_units, + _scalebar_lacks_calibration, + _warn_from_caller, ) if isinstance(scalebar, str): @@ -155,18 +165,16 @@ def with_scan_calibration(scalebar, calibration: dict | None): return _fill_scalebar_calibration(scalebar, calibration["sampling"], calibration["units"]) if scalebar is True: return None - cfg = _resolve_scalebar(scalebar) - if ( - cfg is not None - and cfg.display_units is not None - and _parse_length_units(cfg.units) is None - ): - raise ValueError( - f"display_units={cfg.display_units!r} needs a length calibration, but this " - "scan has none (its scale is in pixels). Set dataset.sampling and " - "dataset.units before detecting the Bragg disks, or give 'sampling' and " - "'units' in the scale bar." + if _scalebar_lacks_calibration(scalebar): + display_units = _scalebar_display_units(scalebar) + dropped = f"; display_units={display_units!r} is ignored" if display_units else "" + _warn_from_caller( + f"This scan has no length calibration, so the scale bar is drawn in pixels" + f"{dropped}. Set dataset.sampling and dataset.units before detecting the " + "Bragg disks, or give 'sampling' and 'units' in the scale bar." ) + if display_units: + scalebar = replace(_resolve_scalebar(scalebar), display_units=None) return scalebar From 744b613a733ad643c1eda41eaf81e0bf165ff935 Mon Sep 17 00:00:00 2001 From: maclariz Date: Mon, 16 Nov 2026 15:28:37 +0000 Subject: [PATCH 4/6] Make scale bar pad_px a gap in image pixels pad_px was passed to AnchoredSizeBar as `pad`, which matplotlib reads as a multiple of the label font size, so the gap did not follow the image at all; scan maps that set it to rows/80 got very large margins on big scans. width_px was also truncated with int(), so 0.5 drew no bar. pad_px is now the gap between the bar (or its box) and the plot edge in image pixels, as ShowParams.Scalebar already documented. A small AnchoredSizeBar subclass converts it to matplotlib's font-size units each time the bar is placed, so it holds after resizing or tight_layout. The default becomes None, which keeps matplotlib's spacing, so plots that never set pad_px look the same; strain and orientation maps use that default too. width_px is passed as a float. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfYfoAEq86paxTeAox --- src/quantem/core/visualization/show_params.py | 7 ++- .../core/visualization/visualization_utils.py | 61 +++++++++++++++---- .../diffraction/orientation_visualization.py | 7 +-- .../diffraction/strain_visualization.py | 2 +- 4 files changed, 56 insertions(+), 21 deletions(-) diff --git a/src/quantem/core/visualization/show_params.py b/src/quantem/core/visualization/show_params.py index 27ef0104..b4e08719 100644 --- a/src/quantem/core/visualization/show_params.py +++ b/src/quantem/core/visualization/show_params.py @@ -243,8 +243,9 @@ class Scalebar: ``None`` picks units automatically from the bar length. width_px : float Thickness of the bar in image pixels. Default 1. - pad_px : float - Padding between bar and plot edge in image pixels. Default 0.5. + pad_px : float | None + Padding between bar and plot edge in image pixels. Default None, + matplotlib's spacing, which scales with the font size. color : str Bar and label colour. Default ``"white"``. loc : ``"lower right"`` | ``"lower left"`` | ``"upper right"`` | ``"upper left"`` @@ -278,7 +279,7 @@ class Scalebar: length: float | None = None display_units: str | None = None width_px: float = 1 - pad_px: float = 0.5 + pad_px: float | None = None color: str = "white" loc: Literal["lower right", "lower left", "upper right", "upper left"] = "lower right" fontsize: int = 12 diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index fb6f1212..39b5a530 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -141,8 +141,10 @@ class ScalebarConfig: automatically from the bar length. width_px : float, default=1 Width of the scale bar in pixels. - pad_px : float, default=0.5 - Padding around the scale bar in pixels. + pad_px : float, optional + Gap between the scale bar (or its box) and the edge of the plot, in + image pixels. If None, matplotlib's default spacing is used, which + scales with the label font size rather than the image. color : str, default="white" Color of the scale bar. loc : str or int, default="lower right" @@ -171,7 +173,7 @@ class ScalebarConfig: length: float | None = None display_units: str | None = None width_px: float = 1 - pad_px: float = 0.5 + pad_px: float | None = None color: str = "white" loc: str | int = "lower right" fontsize: int = 12 @@ -492,6 +494,30 @@ def _normalize_length_units(length_units: float, units: str) -> tuple[float, str return length_A / 1e10, "m" +class _PixelPaddedSizeBar(AnchoredSizeBar): + """AnchoredSizeBar held `pad_px` image pixels from the edge of the axes. + + matplotlib measures `borderpad` in multiples of the label font size, so + a gap in image pixels has to be converted with the current data-to-screen + scale. That is redone every time the bar is placed, so the gap follows + any later change of figure size or layout (e.g. ``tight_layout``). + """ + + def __init__(self, transform, *args, pad_px: float, **kwargs): + super().__init__(transform, *args, borderpad=0.0, **kwargs) + self._pad_px = float(pad_px) + self._pad_transform = transform + + def get_offset(self, *args, **kwargs): + renderer = kwargs.get("renderer", args[-1] if args else None) + if renderer is not None: + (x0, y0), (x1, y1) = self._pad_transform.transform([(0, 0), (1, 1)]) + screen_px_per_image_px = 0.5 * (abs(x1 - x0) + abs(y1 - y0)) + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + self.borderpad = self._pad_px * screen_px_per_image_px / fontsize + return super().get_offset(*args, **kwargs) + + def add_scalebar_to_ax( ax: Axes, array_size: float, @@ -499,7 +525,7 @@ def add_scalebar_to_ax( length_units: float | None, units: str, width_px: float, - pad_px: float, + pad_px: float | None, color: str, loc: str | int, fontsize: int = 12, @@ -528,8 +554,9 @@ def add_scalebar_to_ax( Units to display on the scale bar. width_px : float Width of the scale bar in pixels. - pad_px : float - Padding around the scale bar in pixels. + pad_px : float or None + Gap between the scale bar (or its box) and the edge of the plot, in + image pixels. None uses matplotlib's default spacing. color : str Color of the scale bar. loc : str or int @@ -596,19 +623,27 @@ def add_scalebar_to_ax( fontprops = FontProperties(size=fontsize, weight="bold" if bold else "normal") label_top = loc[:3] == "low" - bar = AnchoredSizeBar( - ax.transData, - length_px, - label, - loc, - pad=pad_px, + bar_kwargs = dict( color=color, frameon=box, label_top=label_top, - size_vertical=int(width_px), + size_vertical=float(width_px), fontproperties=fontprops, sep=2 if label_top else int(round(0.3 * fontsize)), ) + if pad_px is None: + # matplotlib's own spacing, in multiples of the label font size + bar = AnchoredSizeBar(ax.transData, length_px, label, loc, pad=0.5, **bar_kwargs) + else: + bar = _PixelPaddedSizeBar( + ax.transData, + length_px, + label, + loc, + pad=0.3 if box else 0.0, + pad_px=pad_px, + **bar_kwargs, + ) if box: bar.patch.set(facecolor=box_color, edgecolor="none", alpha=box_alpha) if outline_color is not None: diff --git a/src/quantem/diffraction/orientation_visualization.py b/src/quantem/diffraction/orientation_visualization.py index b3271858..fe514c51 100644 --- a/src/quantem/diffraction/orientation_visualization.py +++ b/src/quantem/diffraction/orientation_visualization.py @@ -370,15 +370,14 @@ def _draw_map_scalebar(ax, scalebar, shape) -> None: Accepts None/False (no bar), True, a dict of :class:`ScalebarConfig` fields, a ScalebarConfig or a ``ShowParams.Scalebar``. Every field is - honored. A bar width and padding left at the ScalebarConfig defaults are - scaled to the map size instead, since one pixel is invisible on a scan. + honored. A bar width left at the ScalebarConfig default is scaled to the + map size instead, since a one-pixel bar is invisible on a scan. """ cfg = _resolve_scalebar(scalebar) if cfg is None: return defaults = ScalebarConfig() width_px = shape[0] / 40 if cfg.width_px == defaults.width_px else cfg.width_px - pad_px = shape[0] / 80 if cfg.pad_px == defaults.pad_px else cfg.pad_px add_scalebar_to_ax( ax, array_size=shape[1], @@ -386,7 +385,7 @@ def _draw_map_scalebar(ax, scalebar, shape) -> None: length_units=cfg.length, units=cfg.units, width_px=width_px, - pad_px=pad_px, + pad_px=cfg.pad_px, color=cfg.color, loc=cfg.loc, fontsize=cfg.fontsize, diff --git a/src/quantem/diffraction/strain_visualization.py b/src/quantem/diffraction/strain_visualization.py index e141232d..fa1acb64 100644 --- a/src/quantem/diffraction/strain_visualization.py +++ b/src/quantem/diffraction/strain_visualization.py @@ -273,7 +273,7 @@ def _roi_compose(norm_vals, color_cm): "units": ds_units, "length": None, "width_px": 1, - "pad_px": 0.5, + "pad_px": None, "color": "white" if box and box_color == "black" else "black", "loc": "lower left", "fontsize": 12, From e23a8f859d5ebb5952af355a54e1c927d440239a Mon Sep 17 00:00:00 2001 From: maclariz Date: Mon, 16 Nov 2026 15:49:33 +0000 Subject: [PATCH 5/6] Use None as the scale bar width default so width_px=1 is honoured Scan maps scale an unset bar width to 1/40 of the map height, and told "unset" from "set" by comparing with the default of 1, so an explicit width_px=1 was silently replaced. The default is now None: show_2d draws None as 1 image pixel as before, scan maps scale it, and every width given, including 1, is used as it is. Documented that fractional widths are kept. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfYfoAEq86paxTeAox --- src/quantem/core/visualization/show_params.py | 11 +++++++---- .../core/visualization/visualization_utils.py | 16 +++++++++------- .../diffraction/orientation_visualization.py | 9 ++++----- 3 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/quantem/core/visualization/show_params.py b/src/quantem/core/visualization/show_params.py index b4e08719..8107df43 100644 --- a/src/quantem/core/visualization/show_params.py +++ b/src/quantem/core/visualization/show_params.py @@ -241,8 +241,10 @@ class Scalebar: ``"nm"`` for data calibrated in ``"μm"``, or ``"1/Å"`` for data in ``"1/nm"``. Supports pm, Å, nm, μm, mm, cm, m and their reciprocals. ``None`` picks units automatically from the bar length. - width_px : float - Thickness of the bar in image pixels. Default 1. + width_px : float | None + Thickness of the bar in image pixels; fractions are kept. Default + None: 1 pixel on an image, scaled to the map size on orientation + and phase maps. pad_px : float | None Padding between bar and plot edge in image pixels. Default None, matplotlib's spacing, which scales with the font size. @@ -278,7 +280,7 @@ class Scalebar: units: str = "pixels" length: float | None = None display_units: str | None = None - width_px: float = 1 + width_px: float | None = None pad_px: float | None = None color: str = "white" loc: Literal["lower right", "lower left", "upper right", "upper left"] = "lower right" @@ -294,7 +296,8 @@ def __post_init__(self) -> None: validate_gt(self.sampling, 0, "sampling") if self.length is not None: validate_gt(self.length, 0, "length") - validate_gt(self.width_px, 0, "width_px") + if self.width_px is not None: + validate_gt(self.width_px, 0, "width_px") validate_gt(self.fontsize, 0, "fontsize") validate_gt(self.outline_width, 0, "outline_width") if self.display_units is not None and _parse_length_units(self.display_units) is None: diff --git a/src/quantem/core/visualization/visualization_utils.py b/src/quantem/core/visualization/visualization_utils.py index 39b5a530..ab2fe0f3 100644 --- a/src/quantem/core/visualization/visualization_utils.py +++ b/src/quantem/core/visualization/visualization_utils.py @@ -139,8 +139,10 @@ class ScalebarConfig: Converts between pm, Å, nm, μm, mm, cm and m, or between their reciprocals (e.g. "1/nm" to "1/Å"). If None, units are chosen automatically from the bar length. - width_px : float, default=1 - Width of the scale bar in pixels. + width_px : float, optional + Thickness of the scale bar in image pixels; fractions are kept. If + None, the plot chooses: 1 pixel for an image, or a fraction of the + map size for orientation and phase maps. pad_px : float, optional Gap between the scale bar (or its box) and the edge of the plot, in image pixels. If None, matplotlib's default spacing is used, which @@ -172,7 +174,7 @@ class ScalebarConfig: units: str = "pixels" length: float | None = None display_units: str | None = None - width_px: float = 1 + width_px: float | None = None pad_px: float | None = None color: str = "white" loc: str | int = "lower right" @@ -524,7 +526,7 @@ def add_scalebar_to_ax( sampling: float, length_units: float | None, units: str, - width_px: float, + width_px: float | None, pad_px: float | None, color: str, loc: str | int, @@ -552,8 +554,8 @@ def add_scalebar_to_ax( will be estimated. units : str Units to display on the scale bar. - width_px : float - Width of the scale bar in pixels. + width_px : float or None + Thickness of the scale bar in image pixels. None means 1 pixel. pad_px : float or None Gap between the scale bar (or its box) and the edge of the plot, in image pixels. None uses matplotlib's default spacing. @@ -627,7 +629,7 @@ def add_scalebar_to_ax( color=color, frameon=box, label_top=label_top, - size_vertical=float(width_px), + size_vertical=1.0 if width_px is None else float(width_px), fontproperties=fontprops, sep=2 if label_top else int(round(0.3 * fontsize)), ) diff --git a/src/quantem/diffraction/orientation_visualization.py b/src/quantem/diffraction/orientation_visualization.py index fe514c51..a673cff5 100644 --- a/src/quantem/diffraction/orientation_visualization.py +++ b/src/quantem/diffraction/orientation_visualization.py @@ -7,7 +7,6 @@ from quantem.core.utils.rotations import quat_to_matrix from quantem.core.visualization.visualization_utils import ( - ScalebarConfig, _resolve_scalebar, add_scalebar_to_ax, ) @@ -370,14 +369,14 @@ def _draw_map_scalebar(ax, scalebar, shape) -> None: Accepts None/False (no bar), True, a dict of :class:`ScalebarConfig` fields, a ScalebarConfig or a ``ShowParams.Scalebar``. Every field is - honored. A bar width left at the ScalebarConfig default is scaled to the - map size instead, since a one-pixel bar is invisible on a scan. + honored. With no width_px set, the bar is 1/40 of the map height thick, + since a one-pixel bar is invisible on a scan; any width_px given, + including 1, is used as it is. """ cfg = _resolve_scalebar(scalebar) if cfg is None: return - defaults = ScalebarConfig() - width_px = shape[0] / 40 if cfg.width_px == defaults.width_px else cfg.width_px + width_px = shape[0] / 40 if cfg.width_px is None else cfg.width_px add_scalebar_to_ax( ax, array_size=shape[1], From 36f4153cbd3ca32e2cff48cde83c31c6bfbd3278 Mon Sep 17 00:00:00 2001 From: maclariz Date: Mon, 16 Nov 2026 16:25:21 +0000 Subject: [PATCH 6/6] Draw cluster pole figures in the scan frame, like plot_pole_figure plot_pole_figure shows poles in the scan (image) frame of the orientation maps, column axis c rightward and row axis r downward, but plot_cluster_pole_figure put lab x (r) across and lab y (c) upward. The swap plus flip left the two figures rotated 90 degrees from each other. Plot the cluster means and the overlay as (c, r) with the y axis inverted, and add the same scan-axes glyph, now shared as _draw_scan_axes_glyph. Checked that a single orientation's cluster marker lands on plot_pole_figure's density peak and its overlay marker. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TKw4bfYfoAEq86paxTeAox --- .../diffraction/orientation_visualization.py | 67 +++++++++---------- 1 file changed, 32 insertions(+), 35 deletions(-) diff --git a/src/quantem/diffraction/orientation_visualization.py b/src/quantem/diffraction/orientation_visualization.py index a673cff5..66e57adc 100644 --- a/src/quantem/diffraction/orientation_visualization.py +++ b/src/quantem/diffraction/orientation_visualization.py @@ -1031,6 +1031,28 @@ def _pole_scatter_xy(quats: torch.Tensor, crystal: Crystal, pole) -> np.ndarray: return np.stack((x, y), axis=1) +def _draw_scan_axes_glyph(ax) -> None: + """Scan-axes arrows in the top-left corner of a pole figure. + + Pole figures are drawn in the scan (image) frame of the orientation maps: + c (column) rightward and r (row) downward, so the y axis is inverted. + """ + gx, gy = -1.06, -1.06 + for dx, dy, lbl, ha, va in ( + (0.22, 0.0, "c", "left", "center"), + (0.0, 0.22, "r", "center", "top"), + ): + ax.annotate( + "", + xy=(gx + dx, gy + dy), + xytext=(gx, gy), + arrowprops=dict(arrowstyle="-|>", color="0.3", lw=1.2), + annotation_clip=False, + ) + ax.text(gx + dx * 1.25, gy + dy * 1.25, lbl, fontsize=9, ha=ha, va=va, color="0.3") + ax.text(gx - 0.03, gy - 0.06, "scan axes", fontsize=7, ha="left", va="bottom", color="0.45") + + def plot_cluster_pole_figure( om, clusters: dict, @@ -1042,6 +1064,10 @@ def plot_cluster_pole_figure( ): """Pole figure of the cluster mean orientations, one color per cluster. + Drawn in the scan frame, the same as :func:`plot_pole_figure`: the scan + column axis c to the right and the row axis r downward, so the two + figures can be compared or overlaid directly. + Also available as :meth:`OrientationMap.plot_cluster_pole_figure`. Parameters @@ -1091,9 +1117,10 @@ def plot_cluster_pole_figure( K = clusters["mean_quats"].shape[0] for k in range(K): xy = _pole_scatter_xy(clusters["mean_quats"][k], om.crystal, pole) + # scan frame, as in plot_pole_figure: c (lab y) across, r (lab x) down ax.scatter( - xy[:, 0], xy[:, 1], + xy[:, 0], s=60, marker="h", color=colors[k % len(colors)], @@ -1104,8 +1131,8 @@ def plot_cluster_pole_figure( if overlay is not None: xy = _pole_scatter_xy(overlay["quats"], overlay["crystal"], overlay["pole"]) ax.scatter( - xy[:, 0], xy[:, 1], + xy[:, 0], s=70, marker="D", facecolors="none", @@ -1113,8 +1140,9 @@ def plot_cluster_pole_figure( lw=1.0, label=overlay.get("label", "overlay"), ) + _draw_scan_axes_glyph(ax) ax.set_xlim(-1.15, 1.15) - ax.set_ylim(-1.15, 1.15) + ax.set_ylim(1.2, -1.15) ax.set_aspect("equal") ax.set_xticks([]) ax.set_yticks([]) @@ -1285,38 +1313,7 @@ def plot_pole_figure( for az in range(0, 180, 30): ca, sa = np.cos(np.deg2rad(az)), np.sin(np.deg2rad(az)) ax.plot([-ca, ca], [-sa, sa], color="0.85", lw=0.4) - # compact scan-axes glyph, top-left corner: the pole figure is in - # the scan (image) frame -- c rightward, r downward - gx, gy = -1.06, -1.06 - for dx, dy, lbl, ha, va in ( - (0.22, 0.0, "c", "left", "center"), - (0.0, 0.22, "r", "center", "top"), - ): - ax.annotate( - "", - xy=(gx + dx, gy + dy), - xytext=(gx, gy), - arrowprops=dict(arrowstyle="-|>", color="0.3", lw=1.2), - annotation_clip=False, - ) - ax.text( - gx + dx * 1.25, - gy + dy * 1.25, - lbl, - fontsize=9, - ha=ha, - va=va, - color="0.3", - ) - ax.text( - gx - 0.03, - gy - 0.06, - "scan axes", - fontsize=7, - ha="left", - va="bottom", - color="0.45", - ) + _draw_scan_axes_glyph(ax) if overlay is not None: if "om" in overlay: # raw-histogram contour of another map's pole family