Skip to content

Tick formatters

A Formatter turns a tick's numeric position into its label string. Pass one to Axes.set(xformatter=..., yformatter=...) or to Figure.colorbar(format=...); a "{x:.2f}" template string or any callable is accepted in the same places.

ticker

Tick-label formatters.

A Formatter turns a tick's numeric position into its label string. Pass an instance to Axes.set via xformatter=/yformatter= (or to a colorbar); the active Scale locates the tick positions and the formatter decides how each is written. Labels may contain $...$ math (e.g. LogFormatter emits $10^{k}$), which flows through the same editable-text pipeline as every other label.

Formatters that render a number sign it with MINUS (see fix_minus). The ones that hand back a string you supplied - FixedFormatter, FuncFormatter, StrMethodFormatter, DateFormatter - pass it through untouched, so "%Y-%m-%d" keeps its hyphens.

MINUS module-attribute

MINUS = '−'

Formatter

Base formatter: subclasses implement __call__. Calling a formatter with a tick value (and optional integer position) returns its label.

format_ticks

format_ticks(values) -> list[str]

Label a whole sequence of tick positions (some formatters use the set, e.g. to choose a shared offset/exponent).

Source code in python/pyplotrs/ticker.py
def format_ticks(self, values) -> list[str]:
    """Label a whole sequence of tick positions (some formatters use the set,
    e.g. to choose a shared offset/exponent)."""
    return [self(v, i) for i, v in enumerate(values)]

ScalarFormatter

ScalarFormatter(
    scientific: bool = False,
    power_limits: tuple[int, int] = (-5, 6),
)

Bases: Formatter

Plain decimal formatting. With scientific=True values outside 10**-power_limits[0] .. 10**power_limits[1] render in $m×10^{k}$ mantissa/exponent form.

Source code in python/pyplotrs/ticker.py
def __init__(self, scientific: bool = False,
             power_limits: tuple[int, int] = (-5, 6)) -> None:
    self.scientific = scientific
    self.power_limits = power_limits

FixedFormatter

FixedFormatter(labels)

Bases: Formatter

Return labels from a fixed list by tick index (a fallback "" past the end). Used to back set(xticklabels=...).

Source code in python/pyplotrs/ticker.py
def __init__(self, labels) -> None:
    self.labels = [str(s) for s in labels]

FuncFormatter

FuncFormatter(func: Callable)

Bases: Formatter

Delegate to func(value, pos) (or func(value)).

Source code in python/pyplotrs/ticker.py
def __init__(self, func: Callable) -> None:
    self.func = func

StrMethodFormatter

StrMethodFormatter(fmt: str)

Bases: Formatter

Format via fmt.format(x=value, pos=pos) (e.g. "{x:.2f}").

Source code in python/pyplotrs/ticker.py
def __init__(self, fmt: str) -> None:
    self.fmt = fmt

PercentFormatter

PercentFormatter(
    xmax: float = 1.0,
    decimals: int | None = None,
    symbol: str = "%",
)

Bases: Formatter

Format as a percentage: value / xmax * 100 with symbol appended. decimals=None auto-picks a sensible precision.

Source code in python/pyplotrs/ticker.py
def __init__(self, xmax: float = 1.0, decimals: int | None = None,
             symbol: str = "%") -> None:
    self.xmax = float(xmax)
    self.decimals = decimals
    self.symbol = symbol

EngFormatter

EngFormatter(
    unit: str = "",
    places: int | None = None,
    sep: str = " ",
)

Bases: Formatter

Engineering notation: scale by a power of 1000 and append an SI prefix (k, M, m, µ …), then unit.

Source code in python/pyplotrs/ticker.py
def __init__(self, unit: str = "", places: int | None = None,
             sep: str = " ") -> None:
    self.unit = unit
    self.places = places
    self.sep = sep

LogFormatter

LogFormatter(base: float = 10.0, label_minor: bool = False)

Bases: Formatter

Label decades as $10^{k}$ math; non-decade ticks get "" (unless label_minor is set, which writes them plainly).

Source code in python/pyplotrs/ticker.py
def __init__(self, base: float = 10.0, label_minor: bool = False) -> None:
    self.base = base
    self.label_minor = label_minor

DateFormatter

DateFormatter(fmt: str = '%Y-%m-%d')

Bases: Formatter

Format a day-number tick (see pyplotrs.scales.date2num) with a strftime pattern, e.g. DateFormatter("%Y-%m").

Source code in python/pyplotrs/ticker.py
def __init__(self, fmt: str = "%Y-%m-%d") -> None:
    self.fmt = fmt

get

get(formatter)

Resolve a formatter argument: a Formatter, a str format template ("{x:.2f}"), a callable, or None.

Source code in python/pyplotrs/ticker.py
def get(formatter):
    """Resolve a formatter argument: a ``Formatter``, a ``str`` format
    template (``"{x:.2f}"``), a callable, or ``None``."""
    if formatter is None or isinstance(formatter, Formatter):
        return formatter
    if isinstance(formatter, str):
        return StrMethodFormatter(formatter)
    if callable(formatter):
        return FuncFormatter(formatter)
    raise TypeError(f"expected a Formatter, format string, callable, or None; "
                    f"got {type(formatter).__name__}")

fix_minus

fix_minus(s: str) -> str

Replace the sign in a numeric label with a real MINUS.

Only apply this to strings pyplotrs formatted from a number - never to user text, category names, or strftime output, where a hyphen is a hyphen. Math ($...$) is likewise left alone: the math engine maps - to U+2212 itself, and feeding it a pre-substituted glyph would lose the binary operator's spacing. Disabled by pyplotrs.set_unicode_minus.

Source code in python/pyplotrs/ticker.py
def fix_minus(s: str) -> str:
    """Replace the sign in a *numeric* label with a real ``MINUS``.

    Only apply this to strings pyplotrs formatted from a number - never to user
    text, category names, or ``strftime`` output, where a hyphen is a hyphen.
    Math (``$...$``) is likewise left alone: the math engine maps ``-`` to
    U+2212 itself, and feeding it a pre-substituted glyph would lose the binary
    operator's spacing. Disabled by [`pyplotrs.set_unicode_minus`][pyplotrs.set_unicode_minus].
    """
    return s.replace("-", MINUS) if _UNICODE_MINUS else s