#!/usr/bin/env python
"""
Tick formatters and axis decoration
===================================
This module provides specialized Matplotlib formatters and tick locators for
musical and time/frequency axes. It includes utilities for formatting time,
frequencies (linear and log), musical notes, chords, and chromatic scales.
"""
# mypy: disable-error-code="attr-defined"
# Standard library imports for type checking and future compatibility
from __future__ import annotations
import warnings
# Third-party imports for plotting and numerical operations
from fractions import Fraction
from itertools import product
from typing import TYPE_CHECKING, Any, cast
import matplotlib.axes as mplaxes
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import matplotlib.ticker as mplticker
import matplotlib.transforms as mtransforms
import numpy as np
from matplotlib import colormaps as mcm
# Core and utility imports for audio processing
from .. import core, util
from ..exceptions import (
LibrosaNotImplementedError,
ParameterTypeError,
ParameterValueError,
)
# Type checking imports for development and static analysis
if TYPE_CHECKING:
from collections.abc import Collection, Sequence
from typing import Any
import matplotlib
import matplotlib.axes
import matplotlib.figure
import scipy.interpolate
from matplotlib.colors import Colormap
from .._typing import ArrayLike, _Array1D, _FloatLike_co
# Nominal center frequencies for oct3 bands
_OCT3_FREQUENCIES = np.array(
[
31.5,
40,
50,
63,
80,
100,
125,
160,
200,
250,
315,
400,
500,
630,
800,
1000,
1250,
1600,
2000,
2500,
3150,
4000,
5000,
6300,
8000,
10000,
12500,
16000,
20000,
25000,
# --- ultrasonic up to 800KHz
31500,
40000,
50000,
63000,
80000,
100000,
125000,
160000,
200000,
250000,
315000,
400000,
500000,
630000,
800000,
]
)
class AdaptiveFormatterBase(mplticker.Formatter):
"""Base formatter handling 2-octave span suppression.
Subclasses must implement `_format_tick`.
Parameters
----------
major : bool
If ``True``, ticks are always labeled.
If ``False``, ticks are only labeled if the span is less than 2 octaves.
"""
major: bool
vmin: float | None
vmax: float | None
def __init__(self, major: bool = True):
super().__init__()
self.major = major
self.vmin = None
self.vmax = None
def __call__(self, x: float, pos: int | None = None) -> str:
"""Apply the bounds check, then delegate to subclass formatting."""
if x <= 0:
return ""
assert self.axis is not None
vmin, vmax = self.axis.get_view_interval()
# Handle inverted axes
self.vmin, self.vmax = (vmin, vmax) if vmin <= vmax else (vmax, vmin)
if not self.major and self.vmax > 4 * max(1, self.vmin):
return ""
return self._format_tick(x, pos)
def _format_tick(self, x: float, pos: int | None = None) -> str: # noqa: ARG002
raise LibrosaNotImplementedError
class AdaptiveEngFormatter(AdaptiveFormatterBase):
"""Engineering formatter that limits tick labels to a 2-octave span.
Parameters
----------
major : bool
If ``True``, ticks are always labeled.
If ``False``, ticks are only labeled if the span is less than 2 octaves
**kwargs : keyword arguments
Additional keyword arguments are passed to `matplotlib.ticker.EngFormatter`.
"""
def __init__(self, major: bool = True, **kwargs):
super().__init__(major=major)
self._formatter = mplticker.EngFormatter(**kwargs)
def _format_tick(self, x: float, pos: int | None = None) -> str:
# Delegate string conversion to the wrapped matplotlib formatter
return self._formatter(x, pos)
[docs]
def infer_cmap(
data: np.ndarray,
*,
robust: bool = True,
cmap_seq: str | colors.Colormap = "magma",
cmap_bool: str | colors.Colormap = "gray_r",
cmap_div: str | colors.Colormap = "coolwarm",
div_thresh: float = 0.0,
) -> Colormap:
"""Get a default colormap from the given data.
If the data is boolean, use a black and white colormap.
If the data has both positive and negative values,
use a diverging colormap.
Otherwise, use a sequential colormap.
Parameters
----------
data : np.ndarray
Input data
robust : bool
If True, discard the top and bottom 2% of data when calculating
range.
cmap_seq : str or matplotlib.colors.Colormap
The sequential colormap
cmap_bool : str or matplotlib.colors.Colormap
The boolean colormap
cmap_div : str or matplotlib.colors.Colormap
The diverging colormap
div_thresh : float
The threshold for determining whether to use a diverging colormap.
If the data has values both above and below this threshold, then
a diverging colormap is used.
Returns
-------
cmap : matplotlib.colors.Colormap
The colormap to use for ``data``
See Also
--------
matplotlib.pyplot.colormaps
"""
data = np.atleast_1d(data)
if not isinstance(cmap_seq, colors.Colormap):
cmap_seq = mcm[cmap_seq]
if not isinstance(cmap_bool, colors.Colormap):
cmap_bool = mcm[cmap_bool]
if not isinstance(cmap_div, colors.Colormap):
cmap_div = mcm[cmap_div]
if data.dtype.kind == "b":
return cmap_bool
data = data[np.isfinite(data)]
if robust:
min_p, max_p = 2, 98
else:
min_p, max_p = 0, 100
min_val, max_val = np.percentile(data, [min_p, max_p])
if min_val >= div_thresh or max_val <= div_thresh:
return cmap_seq
return cmap_div
_chroma_ax_types = (
"chroma",
"chroma_h",
"chroma_c",
"chroma_fjs",
)
_cqt_ax_types = (
"cqt_hz",
"cqt_note",
"cqt_svara",
"cqt_oct3",
)
_vqt_ax_types = (
"vqt_hz",
"vqt_note",
"vqt_oct3",
"vqt_fjs",
)
_pitch_ax_types = (
"pitch_hz",
"pitch_note",
"pitch_svara",
"pitch_oct3",
"pitch_fjs",
)
_logfreq_ax_types = (
"logfreq_hz",
"logfreq_note",
"logfreq_svara",
"logfreq_oct3",
)
_freq_ax_types = (
"linear",
"fft",
"hz",
"fft_note",
"fft_svara",
"oct3",
)
_time_ax_types = (
"time",
"h",
"m",
"s",
"ms",
)
_lag_ax_types = (
"lag",
"lag_h",
"lag_m",
"lag_s",
"lag_ms",
)
_misc_ax_types = (
"tempo",
"fourier_tempo",
"mel",
"mel_oct3",
"log",
"tonnetz",
"frames",
)
_AXIS_COMPAT = set(
[(t, t) for t in _misc_ax_types]
+ list(product(_chroma_ax_types, _chroma_ax_types))
+ list(product(_cqt_ax_types, _cqt_ax_types))
+ list(product(_vqt_ax_types, _vqt_ax_types))
+ list(product(_pitch_ax_types, _pitch_ax_types))
+ list(product(_logfreq_ax_types, _logfreq_ax_types))
+ list(product(_freq_ax_types, _freq_ax_types))
+ list(product(_time_ax_types, _time_ax_types))
+ list(product(_lag_ax_types, _lag_ax_types))
)
def _check_axes(axes: mplaxes.Axes | None) -> mplaxes.Axes:
"""Check if "axes" is an instance of an axis object. If not, use `gca`."""
if axes is None:
axes = plt.gca()
elif not isinstance(axes, mplaxes.Axes):
raise ParameterTypeError(f"`axes` must be an instance of matplotlib.axes.Axes. Found type(axes)={type(axes)}")
return axes
def _scale_axes(axes, ax_type, which, tempo_min, tempo_max):
"""Set the axis scaling"""
kwargs = dict()
thresh = "linthresh"
base = "base"
scale = "linscale"
if which == "x":
scaler = axes.set_xscale
limit = axes.set_xlim
else:
scaler = axes.set_yscale
limit = axes.set_ylim
# Map ticker scales
if ax_type in ["mel", "mel_oct3"]:
mode = "symlog"
kwargs[thresh] = 1000.0
kwargs[base] = 2
elif ax_type in [
"cqt",
"cqt_hz",
"cqt_note",
"cqt_svara",
"cqt_oct3",
"logfreq_hz",
"logfreq_note",
"logfreq_svara",
"logfreq_oct3",
"pitch_hz",
"pitch_note",
"pitch_svara",
"pitch_oct3",
"pitch_fjs",
"vqt_hz",
"vqt_note",
"vqt_fjs",
"vqt_oct3",
]:
mode = "log"
kwargs[base] = 2
elif ax_type in ["log", "fft_note", "fft_svara", "log_oct3"]:
mode = "symlog"
kwargs[base] = 2
kwargs[thresh] = float(core.note_to_hz("C2"))
kwargs[scale] = 0.5
elif ax_type in ["tempo", "fourier_tempo"]:
mode = "log"
kwargs[base] = 2
limit(tempo_min, tempo_max)
else:
return
scaler(mode, **kwargs)
def _decorate_axis(
axis,
ax_type,
key="C:maj",
Sa=None,
mela=None,
thaat=None,
unicode=True,
fmin=None,
unison=None,
intervals=None,
bins_per_octave=None,
n_bins=None,
):
"""Configure axis tickers, locators, and labels"""
fmin = util._ensure_hz(fmin)
time_units = {"h": "hours", "m": "minutes", "s": "seconds", "ms": "milliseconds"}
if ax_type == "tonnetz":
axis.set_major_formatter(TonnetzFormatter())
axis.set_major_locator(mplticker.FixedLocator([0, 1, 2, 3, 4, 5]))
axis.set_label_text("Tonnetz")
elif ax_type == "chroma":
axis.set_major_formatter(ChromaFormatter(key=key, unicode=unicode))
degrees = core.key_to_degrees(key)
axis.set_major_locator(
mplticker.FixedLocator(
cast(
"Sequence[float]",
np.add.outer(12 * np.arange(10), degrees, dtype=float).ravel(),
)
)
)
axis.set_label_text("Pitch class")
elif ax_type == "chroma_h":
if Sa is None:
Sa = 0
axis.set_major_formatter(ChromaSvaraFormatter(Sa=Sa, unicode=unicode))
if thaat is None:
# If no thaat is given, show all svara
degrees = np.arange(12)
else:
degrees = core.thaat_to_degrees(thaat)
# Rotate degrees relative to Sa
degrees = np.mod(degrees + Sa, 12)
axis.set_major_locator(
mplticker.FixedLocator(
cast(
"Sequence[float]",
np.add.outer(12 * np.arange(10), degrees, dtype=float).ravel(),
)
)
)
axis.set_label_text("Svara")
elif ax_type == "chroma_c":
if Sa is None:
Sa = 0
axis.set_major_formatter(ChromaSvaraFormatter(Sa=Sa, mela=mela, unicode=unicode))
degrees = core.mela_to_degrees(mela)
# Rotate degrees relative to Sa
degrees = np.mod(degrees + Sa, 12)
axis.set_major_locator(
mplticker.FixedLocator(
cast(
"Sequence[float]",
np.add.outer(12 * np.arange(10), degrees, dtype=float).ravel(),
)
)
)
axis.set_label_text("Svara")
elif ax_type == "chroma_fjs":
if fmin is None:
fmin = core.note_to_hz("C1")
if unison is None:
unison = core.hz_to_note(fmin, octave=False, cents=False)
axis.set_major_formatter(
ChromaFJSFormatter(
intervals=intervals,
unison=unison,
unicode=unicode,
bins_per_octave=bins_per_octave,
)
)
if isinstance(intervals, str) and bins_per_octave > 7:
# If intervals are implicit, generate the first 7 and identify
# them in the sorted set
tick_intervals = core.interval_frequencies(
7,
fmin=1,
intervals=intervals,
bins_per_octave=bins_per_octave,
sort=False,
)
all_intervals = core.interval_frequencies(
bins_per_octave,
fmin=1,
intervals=intervals,
bins_per_octave=bins_per_octave,
sort=True,
)
degrees = util.match_events(tick_intervals, all_intervals)
else:
# If intervals are explicit, tick them all
degrees = np.arange(bins_per_octave)
axis.set_major_locator(mplticker.FixedLocator(degrees)) # type: ignore[arg-type]
axis.set_label_text("Pitch class")
elif ax_type in ["tempo", "fourier_tempo"]:
axis.set_major_formatter(mplticker.ScalarFormatter())
axis.set_major_locator(mplticker.LogLocator(base=2.0))
axis.set_label_text("BPM")
elif ax_type == "time":
axis.set_major_formatter(TimeFormatter(unit=None, lag=False))
axis.set_major_locator(mplticker.MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
axis.set_label_text("Time")
elif ax_type in time_units:
axis.set_major_formatter(TimeFormatter(unit=ax_type, lag=False))
axis.set_major_locator(mplticker.MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
axis.set_label_text(f"Time ({time_units[ax_type]:s})")
elif ax_type == "lag":
axis.set_major_formatter(TimeFormatter(unit=None, lag=True))
axis.set_major_locator(mplticker.MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
axis.set_label_text("Lag")
elif isinstance(ax_type, str) and ax_type.startswith("lag_"):
unit = ax_type[4:]
axis.set_major_formatter(TimeFormatter(unit=unit, lag=True))
axis.set_major_locator(mplticker.MaxNLocator(prune=None, steps=[1, 1.5, 5, 6, 10]))
axis.set_label_text(f"Lag ({time_units[unit]:s})")
elif ax_type in ["cqt_note", "logfreq_note"] or (
ax_type == "pitch_note" and (intervals is None or intervals == "equal")
):
axis.set_major_formatter(NoteFormatter(key=key, unicode=unicode))
# Where is C1 relative to 2**k hz?
log_C1 = np.log2(core.note_to_hz("C1"))
C_offset = 2.0 ** (log_C1 - np.floor(log_C1))
axis.set_major_locator(mplticker.LogLocator(base=2.0, subs=(C_offset,)))
axis.set_minor_formatter(NoteFormatter(key=key, major=False, unicode=unicode))
axis.set_minor_locator(mplticker.LogLocator(base=2.0, subs=C_offset * 2.0 ** (np.arange(1, 12) / 12.0)))
axis.set_label_text("Note")
elif ax_type in ["cqt_svara", "logfreq_svara"] or ax_type == "pitch_svara":
if ax_type == "pitch_svara" and intervals not in (None, "equal"):
raise ParameterValueError("Svara display is not currently supported for non-equal pitch intervals")
if Sa is None:
raise ParameterValueError("Sa frequency is required for svara display formatting")
axis.set_major_formatter(SvaraFormatter(Sa=Sa, mela=mela, unicode=unicode))
# Find the offset of Sa relative to 2**k Hz
sa_offset = 2.0 ** (np.log2(Sa) - np.floor(np.log2(Sa)))
axis.set_major_locator(mplticker.LogLocator(base=2.0, subs=(sa_offset,)))
axis.set_minor_formatter(SvaraFormatter(Sa=Sa, mela=mela, major=False, unicode=unicode))
axis.set_minor_locator(mplticker.LogLocator(base=2.0, subs=sa_offset * 2.0 ** (np.arange(1, 12) / 12.0)))
axis.set_label_text("Svara")
elif ax_type in ["vqt_fjs", "pitch_fjs"]:
if fmin is None:
fmin = float(core.note_to_hz("C1"))
axis.set_major_formatter(
FJSFormatter(
intervals=intervals,
fmin=fmin,
unison=unison,
unicode=unicode,
bins_per_octave=bins_per_octave,
n_bins=n_bins,
)
)
log_fmin = np.log2(fmin)
fmin_offset = 2.0 ** (log_fmin - np.floor(log_fmin))
axis.set_major_locator(mplticker.LogLocator(base=2.0, subs=(fmin_offset,)))
axis.set_minor_formatter(
FJSFormatter(
intervals=intervals,
fmin=fmin,
unison=unison,
unicode=unicode,
bins_per_octave=bins_per_octave,
n_bins=n_bins,
major=False,
)
)
axis.set_minor_locator(
mplticker.FixedLocator(
core.interval_frequencies(
n_bins * 12 // bins_per_octave,
fmin=fmin,
intervals=intervals,
bins_per_octave=12,
) # type: ignore[arg-type]
)
)
axis.set_label_text("Note")
elif ax_type == "vqt_hz" or (ax_type == "pitch_hz" and intervals not in (None, "equal")):
if fmin is None:
fmin = core.note_to_hz("C1")
axis.set_major_formatter(LogHzFormatter())
log_fmin = np.log2(fmin)
fmin_offset = 2.0 ** (log_fmin - np.floor(log_fmin))
axis.set_major_locator(mplticker.LogLocator(base=2.0, subs=(fmin_offset,)))
axis.set_minor_formatter(LogHzFormatter(major=False))
axis.set_minor_locator(
mplticker.LogLocator(
base=2.0,
subs=core.interval_frequencies(12, fmin=fmin_offset, intervals=intervals, bins_per_octave=12), # type: ignore[arg-type]
)
)
axis.set_label_text("Hz")
elif ax_type == "vqt_note" or (ax_type == "pitch_note" and intervals not in (None, "equal")):
if fmin is None:
fmin = core.note_to_hz("C1")
axis.set_major_formatter(NoteFormatter(key=key, unicode=unicode))
log_fmin = np.log2(fmin)
fmin_offset = 2.0 ** (log_fmin - np.floor(log_fmin))
axis.set_major_locator(mplticker.LogLocator(base=2.0, subs=(fmin_offset,)))
axis.set_minor_formatter(NoteFormatter(key=key, unicode=unicode, major=False))
axis.set_minor_locator(
mplticker.LogLocator(
base=2.0,
subs=core.interval_frequencies(12, fmin=fmin_offset, intervals=intervals, bins_per_octave=12), # type: ignore[arg-type]
)
)
axis.set_label_text("Note")
elif ax_type in [
"cqt_hz",
"logfreq_hz",
] or (ax_type == "pitch_hz" and (intervals is None or intervals == "equal")):
axis.set_major_formatter(LogHzFormatter())
log_C1 = np.log2(core.note_to_hz("C1"))
C_offset = 2.0 ** (log_C1 - np.floor(log_C1))
axis.set_major_locator(mplticker.LogLocator(base=2.0))
axis.set_minor_formatter(LogHzFormatter(major=False))
axis.set_minor_locator(mplticker.LogLocator(base=2.0, subs=C_offset * 2.0 ** (np.arange(1, 12) / 12.0)))
axis.set_label_text("Hz")
elif ax_type == "fft_note":
axis.set_major_formatter(NoteFormatter(key=key, unicode=unicode))
# Where is C1 relative to 2**k hz?
log_C1 = np.log2(core.note_to_hz("C1"))
C_offset = 2.0 ** (log_C1 - np.floor(log_C1))
axis.set_major_locator(mplticker.SymmetricalLogLocator(axis.get_transform()))
axis.set_minor_formatter(NoteFormatter(key=key, major=False, unicode=unicode))
axis.set_minor_locator(
mplticker.LogLocator(base=2.0, subs=2.0 ** (np.arange(1, 12) / 12.0)) # type: ignore[arg-type]
)
axis.set_label_text("Note")
elif ax_type == "fft_svara":
axis.set_major_formatter(SvaraFormatter(Sa=Sa, mela=mela, unicode=unicode))
# Find the offset of Sa relative to 2**k Hz
log_Sa = np.log2(Sa)
sa_offset = 2.0 ** (log_Sa - np.floor(log_Sa))
axis.set_major_locator(mplticker.SymmetricalLogLocator(axis.get_transform(), base=2.0, subs=[sa_offset]))
axis.set_minor_formatter(SvaraFormatter(Sa=Sa, mela=mela, major=False, unicode=unicode))
axis.set_minor_locator(mplticker.LogLocator(base=2.0, subs=sa_offset * 2.0 ** (np.arange(1, 12) / 12.0)))
axis.set_label_text("Svara")
elif ax_type in ["mel", "log"]:
axis.set_major_formatter(mplticker.ScalarFormatter())
axis.set_major_locator(mplticker.SymmetricalLogLocator(axis.get_transform()))
axis.set_label_text("Hz")
elif ax_type in ["linear", "hz", "fft"]:
axis.set_major_formatter(mplticker.ScalarFormatter())
axis.set_label_text("Hz")
elif ax_type in [
"oct3",
"cqt_oct3",
"vqt_oct3",
"log_oct3",
"mel_oct3",
"logfreq_oct3",
"pitch_oct3",
]:
# Label once per octave
if ax_type == "mel_oct3":
# Suppress major ticks for frequencies below 100 Hz in mel mode
axis.set_major_locator(mplticker.FixedLocator(_OCT3_FREQUENCIES[5::3])) # type: ignore[arg-type]
else:
axis.set_major_locator(mplticker.FixedLocator(_OCT3_FREQUENCIES[::3])) # type: ignore[arg-type]
axis.set_major_formatter(AdaptiveEngFormatter(major=True, unit="Hz"))
axis.set_label_text("Frequency")
# Minor ticks at the 1/3 octaves
axis.set_minor_locator(mplticker.FixedLocator(_OCT3_FREQUENCIES, nbins=None)) # type: ignore[arg-type]
axis.set_minor_formatter(AdaptiveEngFormatter(major=False, unit="Hz"))
elif ax_type == "frames":
axis.set_label_text("Frames")
elif ax_type in ["off", "none", None]:
axis.set_label_text("")
axis.set_ticks([])
else:
raise ParameterValueError(f"Unsupported axis type: {ax_type}")
def _coord_fft_hz(n: int, sr: float = 22050, n_fft: int | None = None, **_kwargs: Any) -> _Array1D[np.float64]:
"""Get the frequencies for FFT bins"""
if n_fft is None:
n_fft = 2 * (n - 1)
# The following code centers the FFT bins at their frequencies
# and clips to the non-negative frequency range [0, nyquist]
basis = core.fft_frequencies(sr=sr, n_fft=n_fft)
return basis
def _coord_mel_hz(
n: int,
fmin: float | None = 0.0,
fmax: float | None = None,
sr: float = 22050,
htk: bool = False,
**_kwargs: Any,
) -> _Array1D[np.float64]:
"""Get the frequencies for Mel bins"""
if fmin is None:
fmin = 0.0
if fmax is None:
fmax = 0.5 * sr
basis = core.mel_frequencies(n, fmin=fmin, fmax=fmax, htk=htk)
return basis
def _coord_cqt_hz(
n: int,
fmin: _FloatLike_co | str | None = None,
bins_per_octave: int = 12,
sr: float = 22050,
**_kwargs: Any,
) -> _Array1D[np.float64]:
"""Get CQT bin frequencies"""
fmin = util._ensure_hz(fmin)
if fmin is None:
fmin = float(core.note_to_hz("C1"))
# Apply tuning correction
fmin = fmin * 2.0 ** (_kwargs.get("tuning", 0.0) / bins_per_octave)
# we drop by half a bin so that CQT bins are centered vertically
freqs = core.cqt_frequencies(
n,
fmin=fmin,
bins_per_octave=bins_per_octave,
)
if np.any(freqs > 0.5 * sr):
warnings.warn(
"Frequency axis exceeds Nyquist. Did you remember to set all spectrogram parameters in specshow?",
stacklevel=4,
)
return freqs
def _coord_vqt_hz(
n: int,
fmin: _FloatLike_co | str | None = None,
bins_per_octave: int = 12,
sr: float = 22050,
intervals: str | Collection[float] | None = None,
unison: str | None = None, # noqa: ARG001
**_kwargs: Any,
) -> _Array1D[np.float64]:
fmin = util._ensure_hz(fmin)
if fmin is None:
fmin = float(core.note_to_hz("C1"))
if intervals is None:
raise ParameterValueError("VQT axis coordinates cannot be defined without intervals")
freqs = core.interval_frequencies(n, fmin=fmin, intervals=intervals, bins_per_octave=bins_per_octave)
if np.any(freqs > 0.5 * sr):
warnings.warn(
"Frequency axis exceeds Nyquist. Did you remember to set all spectrogram parameters in specshow?",
stacklevel=4,
)
return freqs
def _coord_pitch_hz(
n: int,
fmin: _FloatLike_co | str | None = None,
bins_per_octave: int = 12,
sr: float = 22050,
intervals: str | Collection[float] | None = None,
tuning: float = 0.0,
**kwargs: Any,
) -> _Array1D[np.float64]:
"""Get Pitch bin frequencies"""
fmin = util._ensure_hz(fmin)
if fmin is None:
fmin = float(core.note_to_hz("C1"))
fmin = fmin * 2.0 ** (tuning / bins_per_octave)
if intervals is None or intervals == "equal":
return _coord_cqt_hz(n, fmin=fmin, bins_per_octave=bins_per_octave, sr=sr, tuning=0.0, **kwargs)
return _coord_vqt_hz(n, fmin=fmin, bins_per_octave=bins_per_octave, sr=sr, intervals=intervals, **kwargs)
_coord_logfreq_hz = _coord_cqt_hz
def _coord_chroma(n: int, bins_per_octave: int = 12, **_kwargs: Any) -> np.ndarray:
"""Get chroma bin numbers"""
return np.linspace(0, (12.0 * n) / bins_per_octave, num=n, endpoint=False)
def _coord_tempo(n: int, sr: float = 22050, hop_length: int = 512, **_kwargs: Any) -> np.ndarray:
"""Tempo coordinates"""
basis = core.tempo_frequencies(n + 1, sr=sr, hop_length=hop_length)[1:]
return basis
def _coord_fourier_tempo(
n: int,
sr: float = 22050,
hop_length: int = 512,
win_length: int | None = None,
**_kwargs: Any,
) -> np.ndarray:
"""Fourier tempogram coordinates"""
if win_length is None:
win_length = 2 * (n - 1)
# The following code centers the FFT bins at their frequencies
# and clips to the non-negative frequency range [0, nyquist]
basis = core.fourier_tempo_frequencies(sr=sr, hop_length=hop_length, win_length=win_length)
return basis
def _coord_n(n: int, **_kwargs: Any) -> np.ndarray:
"""Get bare positions"""
return np.arange(n)
def _coord_time(n: int, sr: float = 22050, hop_length: int = 512, **_kwargs: Any) -> np.ndarray:
"""Get time coordinates from frames"""
times: np.ndarray = core.frames_to_time(np.arange(n), sr=sr, hop_length=hop_length)
return times
def _same_axes(x_axis, y_axis, xlim, ylim):
"""Check if two axes are similar, used to determine squared plots"""
axes_compatible_and_not_none = (x_axis, y_axis) in _AXIS_COMPAT
axes_same_lim = xlim == ylim
return axes_compatible_and_not_none and axes_same_lim
def _radian_formatter(x, pos): # noqa: ARG001
# pos is required by matplotlib's FuncFormatter calling convention and is unused here
"""Format a tick value (in radians) as a rational multiple of pi"""
m = x / np.pi
# hard to imagine going finer than pi/16 (11°)
frac = Fraction(m).limit_denominator(16)
num, den = frac.numerator, frac.denominator
if num == 0:
return " 0"
sign = "-" if num * den < 0 else " "
num_abs = abs(num)
# Build numerator string
coeff = "" if num_abs == 1 else str(num_abs)
if den == 1:
return f"{sign}{coeff}π"
else:
return f"{sign}{coeff}π/{den}"
[docs]
def colorbar_phase(
im: matplotlib.cm.ScalarMappable,
*,
numticks: int = 9,
ax: matplotlib.axes.Axes | None = None,
fig: matplotlib.figure.FigureBase | None = None,
**kwargs: Any,
) -> matplotlib.colorbar.Colorbar:
"""Attach a colorbar to an image representing phase data in radians.
The colorbar will display ticks at rational multiples of π.
Parameters
----------
im : matplotlib.cm.ScalarMappable
The image to which the colorbar will be attached.
Generally this will be a `matplotlib.image.AxesImage` or `matplotlib.collections.QuadMesh`
as returned by `specshow`.
numticks : int > 0
The number of ticks to display on the colorbar.
Default is 9, corresponding to multiples of π/4.
ax : matplotlib.axes.Axes or None
The axes to which the colorbar will be attached.
If None, the colorbar will be attached to the axes of `im`.
fig : matplotlib.figure.Figure, SubFigure, or None
The figure to which the colorbar will be attached.
If None, the colorbar will be attached to the figure of `im`.
**kwargs
Additional keyword arguments to pass to `fig.colorbar`.
Returns
-------
cbar : matplotlib.colorbar.Colorbar
The created colorbar object.
See Also
--------
specshow
colorbar_db
matplotlib.colorbar.Colorbar
Examples
--------
Attach a colorbar to a phase spectrogram
>>> import matplotlib.pyplot as plt
>>> import librosa
>>> y, sr = librosa.loadx("trumpet")
>>> S = librosa.stft(y)
>>> fig, ax = plt.subplots()
>>> im = librosa.display.specshow(
... S, ax=ax, y_axis="log", x_axis="time", vscale="phase"
... )
>>> librosa.display.colorbar_phase(im)
>>> plt.show()
Attach a colorbar to one subplot axes, and show as multiples of π/3.
>>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True)
>>> im_mag = librosa.display.specshow(
... S, ax=ax[0], y_axis="log", x_axis="time", vscale="dBFS"
... )
>>> cbar = librosa.display.colorbar_db(im_mag, ax=ax[0], label="dBFS")
>>> im_ph = librosa.display.specshow(
... S, ax=ax[1], y_axis="log", x_axis="time", vscale="dphase"
... )
>>> cbar = librosa.display.colorbar_phase(im_ph, ax=ax[1], numticks=7)
>>> ax[0].label_outer()
>>> plt.show()
"""
if fig is None:
fig = im.figure
if ax is None:
ax = im.axes
kwargs.setdefault("label", "radians")
kwargs.setdefault("ticks", mplticker.LinearLocator(numticks=numticks))
kwargs.setdefault("format", mplticker.FuncFormatter(_radian_formatter))
cbar = fig.colorbar(
im,
ax=ax,
**kwargs,
)
return cbar
[docs]
def colorbar_db(
im: matplotlib.cm.ScalarMappable,
*,
ax: matplotlib.axes.Axes | None = None,
fig: matplotlib.figure.FigureBase | None = None,
format: str | mplticker.Formatter = "% -3.f",
**kwargs: Any,
) -> matplotlib.colorbar.Colorbar:
"""Attach a colorbar to an image representing decibel-scaled data.
Parameters
----------
im : matplotlib.cm.ScalarMappable
The image to which the colorbar will be attached.
Generally this will be a `matplotlib.image.AxesImage` or `matplotlib.collections.QuadMesh`
as returned by `specshow`.
ax : matplotlib.axes.Axes or None
The axes to which the colorbar will be attached.
If None, the colorbar will be attached to the axes of `im`.
fig : matplotlib.figure.Figure, SubFigure, or None
The figure to which the colorbar will be attached.
If None, the colorbar will be attached to the figure of `im`.
format : str
The format string for the colorbar ticks.
Default is "% -3.f", which displays integer values.
You can change this to a different format if needed.
**kwargs
Additional keyword arguments to pass to `fig.colorbar`.
Returns
-------
cbar : matplotlib.colorbar.Colorbar
The created colorbar object.
See Also
--------
specshow
colorbar_phase
matplotlib.colorbar.Colorbar
Examples
--------
Attach a colorbar to a magnitude spectrogram
>>> import matplotlib.pyplot as plt
>>> import librosa
>>> y, sr = librosa.loadx("trumpet")
>>> S = librosa.stft(y)
>>> fig, ax = plt.subplots()
>>> im = librosa.display.specshow(
... S, ax=ax, y_axis="log", x_axis="time", vscale="dB"
... )
>>> librosa.display.colorbar_db(im)
>>> plt.show()
Attach a colorbar to one subplot axes. We can also set a label for the colorbar.
>>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True)
>>> im_mag = librosa.display.specshow(
... S, ax=ax[0], y_axis="log", x_axis="time", vscale="dBFS"
... )
>>> cbar = librosa.display.colorbar_db(im_mag, ax=ax[0], label="dBFS")
>>> im_ph = librosa.display.specshow(
... S, ax=ax[1], y_axis="log", x_axis="time", vscale="dphase"
... )
>>> cbar = librosa.display.colorbar_phase(im_ph, ax=ax[1])
>>> ax[0].label_outer()
>>> plt.show()
"""
if fig is None:
fig = im.figure
if ax is None:
ax = im.axes
kwargs.setdefault("label", "dB")
cbar = fig.colorbar(
im,
ax=ax,
format=format,
**kwargs,
)
return cbar