Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/jmrplens/phonometry. Standards-conformant acoustics library for Python: measurement and metrology, docs.jmrp.io/phonometry
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611# Copyright (c) 2026. Jose Manuel Requena Plens"""The shared look of every documentation figure: palette, theme and saving.
One subject, in three parts that cannot be separated. The palette and thetheme state are the same names read by every generator (``COLOR_FG``,``COLOR_GRID``, ``CMAP_FIELD`` ...), rebound by :func:`set_theme` when the runswitches between the light and dark pages of the site. :func:`save_figure` isthe only writer: it translates the figure, adds the language/theme suffixesand chooses deterministic SVG or lossless WebP, which is what makes ``makegraphs`` byte-stable and lets CI diff it. The rest is the styling vocabularythe figures apply to their axes, plus :func:`measure_weighting_response`, themeasurement the weighting figures are drawn from and the tests guard."""
from __future__ import annotations
import osfrom typing import TYPE_CHECKING, Any, Literal
# The annotation recorder sits at the top of ``scripts/``, next to the checker# that reads what it writes, exactly as the language one does. No sys.path# guard here, unlike the one .i18n carries: anything that can import# ``figures.theme`` already has ``scripts/`` on the path, because that is the# directory this package sits in. The guard would also cost something real --# a bare ``sys.path.insert(...)`` is a module-level expression, which is what# ``scripts/animation_fingerprint.py`` hashes to decide whether a clip has to# be re-rendered, so writing one here would restamp all forty-two clips for a# hook that cannot move a frame.import figure_annotation_audit as _annotationsimport figure_tick_audit as _ticksimport matplotlib.pyplot as pltimport numpy as npfrom scipy import signal as scipy_signal
from phonometry._plot.common import _register_field_dark_cmap
from . import _publishfrom .i18n import _LANG_SUFFIX, _translate_figure, audit_figure
if TYPE_CHECKING: from collections.abc import Sequence
from matplotlib.axes import Axes from matplotlib.backend_bases import GraphicsContextBase, RendererBase from matplotlib.figure import Figure from matplotlib.font_manager import FontProperties from matplotlib.path import Path from matplotlib.patheffects import PathEffectRenderer from matplotlib.text import Text from matplotlib.transforms import Transform from matplotlib.typing import ColorType
# Constants for professional stylingLABEL_FREQ_HZ = "Frequency [Hz]"LABEL_LEVEL_DB = "Level [dB]"COLOR_PRIMARY = "#1f77b4"COLOR_SECONDARY = "#d62728"COLOR_TERTIARY = "#2ca02c"# The fourth series colour, the same purple the library palette carries as# ``_C_QUATERNARY``. Named here because the CSS "purple" (#800080) that a# figure reaches for instead is too dark to draw a line on the dark page.COLOR_QUATERNARY = "#9467bd"COLOR_GRID = "#e0e0e0"# Neutral for de-emphasised *data* (a context bar, a reference series): mid# grey reads on both pages, unlike COLOR_GRID, which is tuned to disappear# into the one it is drawn on.COLOR_MUTED = "#9e9e9e"
# Shading for an *ordered* scale, the evaluation zones of ISO 20816 and# ISO 10816 above all. The series colours were used for these, and a# categorical palette on an ordered scale tells the reader the opposite of# what the scale says: zone B, "unrestricted operation", came out red and# zone C, "limited operation", came out green, so the better of the two# looked like the alarming one and zone D, damage, was a neutral grey. These# run one way, calm to alarming, and the letter drawn in each band and the# order of the bands themselves repeat the same information for a reader who# does not separate red from green.COLOR_ZONE_A = "#2ca02c"COLOR_ZONE_B = "#b8a70b"COLOR_ZONE_C = "#e07b1f"COLOR_ZONE_D = "#d62728"#: The four in order, for a figure that zips them against its own band edges.COLOR_ZONES = (COLOR_ZONE_A, COLOR_ZONE_B, COLOR_ZONE_C, COLOR_ZONE_D)
# Theme state: every figure is generated twice (light + "_dark" suffix).# COLOR_FG replaces literal black so annotations stay visible on dark bg.COLOR_FG = "black"# Solid backing for a text box that has to stay readable over the plotted# data: a shade off the page rather than the page itself, so the box reads as# a panel and its edge is not the only thing separating it from the figure.COLOR_PANEL = "#f0f2f5"_FILENAME_SUFFIX = ""
# The dark-theme wave-field colormap (berlin with its centre bias subtracted# so zero maps to true black) now lives in the library, where the result# ``.plot()`` renderers pick it whenever the axes background is dark; the# clips address it by name, so it is registered eagerly here._register_field_dark_cmap()
# Theme-dependent wave-field styling, switched by set_theme(): the diverging# colormap of the instantaneous-pressure/velocity panels (zero maps to the# page background on both themes) and the ink/halo pair of the annotations# drawn *inside* those fields. Sequential magma panels (RMS maps, level maps)# are theme-independent and keep their hardcoded white ink.CMAP_FIELD = "RdBu_r"FIELD_INK = "black"FIELD_STROKE = "white"
# Where a sequential colormap is read for a *family of curves*, per theme. A# ramp like viridis runs from a near-black purple to a near-white yellow, so# neither end can be drawn on both pages: sampled from 0.05, the first two# curves of a six-curve family were within a level and a half of the dark# page. Each theme therefore reads the stretch of the ramp its own page leaves# room for, and both stretches keep every entry clear of the page it is drawn# on. This is not the wave-field colormap above: that one maps a *signed# field* onto a page, this one picks apart curves that share an axis._SERIES_SPAN_LIGHT = (0.05, 0.85)_SERIES_SPAN_DARK = (0.32, 1.0)_SERIES_SPAN = _SERIES_SPAN_LIGHT
# Global matplotlib configurationplt.rcParams.update( { "font.size": 10, "axes.grid": True, "grid.alpha": 0.5, "grid.linestyle": "--", "figure.figsize": (10, 6), "figure.dpi": 150, "savefig.bbox": "tight", })
def series_colors(count: int, cmap: str = "viridis") -> np.ndarray: """``count`` colours off ``cmap``, over the span the current page allows.
The one call every family of curves that shares an axis should use: ``ax.plot(..., color=colour)`` for each of ``series_colors(len(curves))``. Sampling the colormap directly picks up both of its unusable ends, and the unusable end is a different one on each theme.
:param count: Number of curves in the family. :param cmap: Any sequential matplotlib colormap name. :return: An ``(count, 4)`` RGBA array, dark-to-light along the ramp. """ lo, hi = _SERIES_SPAN return np.asarray(plt.get_cmap(cmap)(np.linspace(lo, hi, count)))
def set_theme(*, dark: bool) -> None: """Switch between the light (default) and dark documentation themes.""" global COLOR_FG, COLOR_GRID, COLOR_PANEL, _FILENAME_SUFFIX global CMAP_FIELD, FIELD_INK, FIELD_STROKE, _SERIES_SPAN if dark: plt.style.use("dark_background") COLOR_FG = "white" COLOR_GRID = "#555555" COLOR_PANEL = "#1c2128" _FILENAME_SUFFIX = "_dark" CMAP_FIELD = "phonometry_field_dark" FIELD_INK = "white" FIELD_STROKE = "black" _SERIES_SPAN = _SERIES_SPAN_DARK else: plt.style.use("default") COLOR_FG = "black" COLOR_GRID = "#e0e0e0" COLOR_PANEL = "#f0f2f5" _FILENAME_SUFFIX = "" CMAP_FIELD = "RdBu_r" FIELD_INK = "black" FIELD_STROKE = "white" _SERIES_SPAN = _SERIES_SPAN_LIGHT _publish( COLOR_FG=COLOR_FG, COLOR_GRID=COLOR_GRID, COLOR_PANEL=COLOR_PANEL, _FILENAME_SUFFIX=_FILENAME_SUFFIX, CMAP_FIELD=CMAP_FIELD, FIELD_INK=FIELD_INK, FIELD_STROKE=FIELD_STROKE, ) plt.rcParams.update( { "font.size": 10, "axes.grid": True, "grid.alpha": 0.5, "grid.linestyle": "--", "figure.figsize": (10, 6), "figure.dpi": 150, "savefig.bbox": "tight", } )
# Figures kept as raster (lossless WebP) because SVG would be strictly heavier,# for two reasons:# * raster-backed (pcolormesh / specgram): the SVG would only wrap a base64# bitmap several times larger than the raster;# * dense time series (thousands of vertices): every sample becomes a path# coordinate, so the SVG runs 5.5-7.75x the raster (schroeder_decay# 105->820 KB, calibration_stability 99->759 KB, impulse_response# 134->747 KB, measured against the earlier PNG encoding).# Both clear the ~4.5x "SVG no longer wins" bar; everything else is a vector plot# written as deterministic SVG (moderate 2.4x cases like sel_concept /# ln_levels_example stay SVG -- below the bar, and vector crispness is worth it)._RASTER_FIGURES = frozenset( { "spectrogram_example", # imshow raster: the STFT cells would bloat an SVG (and the repo's # figure policy keeps rasters out of SVG files). "calibrated_spectrogram", "excitation_signals", "schroeder_decay", "calibration_stability", "impulse_response", "numerical_propagation", "atmospheric_refraction", "airport_contour", "fdtd_simulation", # The launcher field and the rasterised metadiffuser mask are both # imshow of a cell grid: hundreds of thousands of cells, so the SVG # would be far heavier than the raster (as for fdtd_simulation). "fdtd_plane_wave_launch", "metadiffuser_meshed_panel", "elastic_halfspace_waves", "scholte_interface_wave", # Dense reflectogram: hundreds of image-source stems/markers make the # SVG far heavier than the raster (as for schroeder_decay above). "image_source_reflectogram", # Dense time series (tens of thousands of vertices), as for # calibration_stability above: the noise-floor traces of the # correlation normalizations make the SVG several times the raster. "correlation_normalizations", # Ten seconds of raw waveform at 48 kHz: half a million vertices, # same trade as calibration_stability above. "signal_provenance", })
# PLR0913 and FBT: the parameters are matplotlib's draw_text signature.def _draw_path_effect_text( # noqa: PLR0913 self: PathEffectRenderer, gc: GraphicsContextBase, x: float, y: float, s: str, prop: FontProperties, angle: float, ismath: bool | Literal["TeX"] = False, # noqa: FBT001, FBT002 mtext: Text | None = None,) -> None: """``PathEffectRenderer.draw_text`` while :func:`svg_text` writes a drawing.
matplotlib draws a text with a path effect (the halo round a label laid over a moving field) by turning the whole string into one outline and handing it to each effect, the plain one included, so the SVG gets two bare paths and none of the string comment and placed glyphs every figure gate reads a text by: the label was invisible to all of them. Here the effects that add something (the halo's stroke) still draw that outline, and the plain text is drawn by the SVG renderer itself, as any other label, with its string. What lands on the page is the same: the same halo under the same letters in the same colour. """ from matplotlib.backend_bases import RendererBase from matplotlib.patheffects import AbstractPathEffect, Normal, PathEffectRenderer
class _Added(AbstractPathEffect): """A ``with...`` effect without the plain draw it ends with."""
def __init__(self, effect: AbstractPathEffect) -> None: super().__init__() self._effect = effect
def draw_path( self, renderer: RendererBase, gc: GraphicsContextBase, tpath: Path, affine: Transform, # N803: matplotlib's own name for the parameter. rgbFace: ColorType | None = None, # noqa: N803 ) -> None: from typing import cast
base = cast("type[AbstractPathEffect]", type(self._effect).__mro__[1]) base.draw_path(self._effect, renderer, gc, tpath, affine, rgbFace)
for effect in self._path_effects: if isinstance(effect, Normal): self._renderer.draw_text(gc, x, y, s, prop, angle, ismath, mtext) continue # ``withStroke`` and its siblings are made by matplotlib's # ``_subclass_with_normal``: a subclass of the effect named for it, # whose draw is the effect's and then the plain one. base = type(effect).__mro__[1] with_normal = type(effect).__name__ == f"with{base.__name__}" RendererBase.draw_text( PathEffectRenderer( [_Added(effect) if with_normal else effect], self._renderer ), gc, x, y, s, prop, angle, ismath, mtext, ) if with_normal: self._renderer.draw_text(gc, x, y, s, prop, angle, ismath, mtext)
def svg_text(fig: Figure, **kwargs: Any) -> str: """*fig* drawn as the SVG :func:`save_figure` writes, returned as text.
The one place a drawing becomes an SVG: the figures are saved through it, and so is every frame of a clip when ``scripts/clip_frame_audit.py`` holds it to the gates the figures pass, so a frame is read in exactly the form those gates were written for. ``kwargs`` go to ``Figure.savefig``.
Element ids come from a fixed ``svg.hashsalt``, so the same drawing gives the same bytes, and the date is left out of the metadata. A text drawn with a path effect is written as a text with its string, its halo under it (:func:`_draw_path_effect_text`), so the gates read it as they read any other label. """ import io
import generated_assets from matplotlib.patheffects import PathEffectRenderer
plt.rcParams["svg.hashsalt"] = "phonometry" # Text is drawn as outlines, not as <text>. Keeping it as text made a # figure's typography depend on the machine reading it, and for half # the corpus that dependency was visible: # # A label with any mathtext in it is not laid out by the viewer. The # whole string goes through matplotlib's mathtext, which emits one # <tspan> per glyph carrying its own absolute ``x`` -- and those # positions are computed from DejaVu Sans metrics. The file, meanwhile, # asked for a *generic* family, so the viewer set those glyphs in its # own sans (Helvetica on iOS/macOS, Roboto on Android, Arial/Segoe on # Windows, whatever fontconfig picks on Linux) at DejaVu's advances. # Narrower glyphs on wider advances read as letter-spaced prose: the # title of ln_levels_example shipped as "S t a t i s t i c a l". A # label with no mathtext escaped it, being written as one <text> the # viewer is free to shape -- so the defect landed on exactly the # figures carrying mathematics, and grew with every one added. # # The generic family was itself the fix for the previous round of this: # matplotlib writes mathtext with a bare "DejaVu Sans" and no generic # fallback, so a viewer without that font fell back to a *serif*. Both # failures are the same failure -- the drawn result depending on the # reader's font stack -- and outlines end the dependency rather than # trading one symptom for the next. It also drops the STIX exception # that fix needed (radicals and extensible delimiters are drawn from a # dedicated font at a size matched to the glyph beside them, which # rewriting the family silently broke). # # Reproducibility, which is why 'none' was chosen originally, is not # lost: the outlines come from the DejaVu build that matplotlib itself # ships, so they are pinned by the pinned matplotlib, and # check_figures.py compares structure plus numbers within a tolerance # rather than bytes. The report fiches have drawn their plot text as # paths all along (see phonometry._report._layout), so this is the two # halves of the project agreeing rather than a new departure. # # What it costs: the text of a committed .svg is no longer text, so it # cannot be selected in an editor or found with Ctrl-F. Nothing # downstream wanted it. Every figure is embedded as <img>, where the # internal DOM is not exposed to assistive technology (the alt text # is, and ThemeImage.astro refuses to render without one), and in a # figure with mathematics that text layer was already unreadable -- # thirty positioned tspans with the glyphs in layout order, as # check_figure_language.py had to work around. plt.rcParams["svg.fonttype"] = "path" kwargs.setdefault("metadata", {"Date": None}) # Through a buffer and generated_assets.compact_svg: the coordinates # are cut to what a display can resolve and the indentation, DOCTYPE # and metadata come off, a sixth of every file. Reversing the SVG_TOL # relationship: the comparison in check_figures.py accepts one # rounding quantum, which is what two machines either side of a # boundary differ by after this. drawn = io.StringIO() PathEffectRenderer.draw_text = _draw_path_effect_text # type: ignore[method-assign, assignment] try: fig.savefig(drawn, format="svg", **kwargs) finally: del PathEffectRenderer.draw_text return generated_assets.compact_svg(drawn.getvalue())
def save_figure(output_dir: str, filename: str, **kwargs: Any) -> None: """Translate, theme-suffix and save the current figure.
Vector figures are written as SVG made byte-reproducible with a fixed ``svg.hashsalt`` (deterministic element ids), ``svg.fonttype = "path"`` (text drawn as glyph outlines, for the reason spelled out in :func:`svg_text`) and no date metadata -- so ``make graphs`` is stable and CI can diff it. The figures in :data:`_RASTER_FIGURES` stay raster (SVG would be heavier), written as lossless WebP: matplotlib renders the canvas to an in-memory PNG with the version-stamped ``Software`` chunk (and any date) stripped, and Pillow re-encodes those exact pixels with the exhaustive ``method=6`` search, whose output is fixed by the input, so the WebP bytes are reproducible across matplotlib builds and runs. In both cases ``filename`` may carry any extension; the real one is chosen here. """ # This function is the last user of ``os`` here, and the imports of a # module a clip reaches are hashed into scripts/animation_fingerprints.txt: # moving it to pathlib drops the import and asks every clip for a # re-render that would draw the very same frames. stem = os.path.splitext(filename)[0] # noqa: PTH122 audit_figure(stem) _translate_figure(plt.gcf()) if not _FILENAME_SUFFIX: # Two passes in four, and after the translation rather than before it. # The dark twin of a pass is the same drawing in other colours, so the # annotation measurement -- which costs several extra renders -- is # taken on the light pass only. Both languages are measured, because # they are not the same drawing: Spanish prose is longer, so a label # that clears a curve in English grows into it in Spanish. That is # what puts this after the translation, and it is also why the record # is keyed by the asset name with the language suffix on it. _annotations.audit(plt.gcf(), f"{stem}{_LANG_SUFFIX}") # The tick labels are measured on the same passes and for the same # reason: a Spanish label carries a decimal comma and a longer word. _ticks.audit(plt.gcf(), f"{stem}{_LANG_SUFFIX}") ext = "webp" if stem in _RASTER_FIGURES else "svg" # Kept on ``os`` for the reason given at the stem above. path = os.path.join(output_dir, f"{stem}{_LANG_SUFFIX}{_FILENAME_SUFFIX}.{ext}") # noqa: PTH118 if ext == "svg": fig = plt.gcf() # A ``str`` path, for the reason given at the stem above. with open(path, "w", encoding="utf-8") as handle: # noqa: PTH123 handle.write(svg_text(fig, **kwargs)) # ``pyplot.savefig``, which wrote the figures before ``svg_text`` # did, repaints the canvas after the save; kept, so a generator that # saves or measures the same figure again finds it as it did. fig.canvas.draw_idle() return import io
from PIL import Image
# Render the raster figures at 300 dpi so they stay crisp on # high-density displays and when zoomed in the docs. Individual call # sites may still override this. kwargs.setdefault("dpi", 300) # Drop matplotlib's version-stamped Software chunk (and any date). Merge # instead of setdefault: a caller-supplied metadata dict must not silently # reintroduce the version-dependent chunks. kwargs["metadata"] = {"Software": None, "Date": None, **kwargs.get("metadata", {})} with io.BytesIO() as buffer: plt.savefig(buffer, format="png", **kwargs) buffer.seek(0) with Image.open(buffer) as image: # Lossless WebP: identical pixels to the rendered canvas at roughly # half the optimized-PNG size (flat-color plot areas compress better # lossless than lossy). method=6 is the slowest, most exhaustive # encoder search; its output is a pure function of the input pixels, # so the committed bytes are byte-stable across runs. image.save(path, "WEBP", lossless=True, quality=100, method=6)
def apply_axis_styling( ax: Axes, title: str, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None,) -> None: """Apply consistent styling to plots.""" ax.set_title(title, pad=12) ax.set_xlabel(LABEL_FREQ_HZ) ax.set_ylabel(LABEL_LEVEL_DB) ax.grid(which="major", color=COLOR_GRID, linestyle="-") ax.grid(which="minor", color=COLOR_GRID, linestyle=":", alpha=0.4)
if xlim: ax.set_xlim(xlim) if ylim: ax.set_ylim(ylim)
# Standard Octave Ticks xticks = [16, 31.5, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] xticklabels = [ "16", "31.5", "63", "125", "250", "500", "1k", "2k", "4k", "8k", "16k", ] ax.set_xticks(xticks) ax.set_xticklabels(xticklabels)
def plot_psd( ax: Axes, x: np.ndarray, fs: int, label: str = "Raw Signal PSD", color: str = "gray", alpha: float = 0.3,) -> None: """Calculate and plot the Power Spectral Density of the raw signal.""" # Use Welch's method for a smooth PSD estimate f, Pxx = scipy_signal.welch(x, fs, nperseg=4096)
# Convert to dB (relative to max to match SPL scale roughly or just show shape) # Since SPL is calibrated differently, we just want to show the 'shape' of the spectrum # in the background. We can normalize Pxx to match the peak of the octave bands roughly # or just plot it as is if we had calibrated units. # Here we'll just plot relative dB
# Avoid log(0) Pxx_db = 10 * np.log10(Pxx + 1e-12)
# Normalize PSD peak to 0 dB for visualization shape, then shift down? # Or better: don't normalize, just plot. But PSD density vs Octave Band Power (integrated) # are different units (dB/Hz vs dB). # So we will plot it on a secondary Y axis or just scaled to fit nicely in background.
# Let's shift it so its mean roughly aligns with the mean of the SPL for visualization # This is purely for qualitative comparison of "where the energy is".
ax.semilogx(f, Pxx_db, color=color, alpha=alpha, linewidth=1, label=label, zorder=0)
def measure_weighting_response( fs: int, curve: Literal["A", "B", "C", "D", "G", "AU", "468", "Z"], freqs: np.ndarray | None = None,) -> tuple[np.ndarray, np.ndarray]: """Measure a weighting curve the way the docs figure plots it: impulse response through the real filter path, evaluated with ``freqz`` (DTFT of the measured response).
The impulse is placed at the CENTER of the buffer: the high-accuracy weighting path resamples with polyphase FIRs, and an impulse at sample 0 loses the anti-causal half of the interpolation kernel (edge truncation), which once shipped a figure with curves ~2.4 dB low. Centering only adds linear phase, which does not affect the magnitude.
:param fs: Sample rate in Hz. :param curve: 'A', 'B', 'C', 'D', 'G', 'AU', '468' or 'Z'. :param freqs: Optional exact frequencies to evaluate; defaults to a dense 8192-point grid for plotting. :return: Tuple (frequencies, magnitude in dB). """ from phonometry import filters
impulse = np.zeros(fs) impulse[fs // 2] = 1.0 weighted = filters.weighting_filter(impulse, fs, weighting=curve)
worn = 8192 if freqs is None else np.asarray(freqs, dtype=float) w, h = scipy_signal.freqz(weighted, [1], worN=worn, fs=fs) mag_db = 20 * np.log10(np.abs(h) + 1e-9) if freqs is None: # Drop the 0 Hz point: it cannot be drawn on a log frequency axis. return w[1:], mag_db[1:] return w, mag_db
# ---------------------------------------------------------------------------# Building & structure-borne result figures (WP: guide figure coverage).# Each figure is a realistic user result: example data -> real function -># result object, drawn the way the result's own .plot() presents it.# ---------------------------------------------------------------------------_THIRD_OCTAVE_16 = [ 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150,]
def _band_index_axis( ax: Axes, freqs: Sequence[float] | np.ndarray, fontsize: int = 8) -> np.ndarray: """Rotated nominal band labels on an index axis (band-data figures).""" x = np.arange(len(freqs)) ax.set_xticks(x) ax.set_xticklabels( [f"{b:g}" for b in np.asarray(freqs)], rotation=45, fontsize=fontsize ) ax.set_xlabel(LABEL_FREQ_HZ) return x