GitHub Viewer
"""
Tick locating and formatting
============================
This module contains classes for configuring tick locating and formatting.
Generic tick locators and formatters are provided, as well as domain specific
custom ones.
Although the locators know nothing about major or minor ticks, they are used
by the Axis class to support major and minor tick locating and formatting.
.. _tick_locating:
.. _locators:
Tick locating
-------------
The Locator class is the base class for all tick locators. The locators
handle autoscaling of the view limits based on the data limits, and the
choosing of tick locations. A useful semi-automatic tick locator is
`MultipleLocator`. It is initialized with a base, e.g., 10, and it picks
axis limits and ticks that are multiples of that base.
The Locator subclasses defined here are:
======================= =======================================================
`AutoLocator` `MaxNLocator` with simple defaults. This is the default
tick locator for most plotting.
`MaxNLocator` Finds up to a max number of intervals with ticks at
nice locations.
`LinearLocator` Space ticks evenly from min to max.
`LogLocator` Space ticks logarithmically from min to max.
`MultipleLocator` Ticks and range are a multiple of base; either integer
or float.
`FixedLocator` Tick locations are fixed.
`IndexLocator` Locator for index plots (e.g., where
``x = range(len(y))``).
`NullLocator` No ticks.
`SymmetricalLogLocator` Locator for use with the symlog norm; works like
`LogLocator` for the part outside of the threshold and
adds 0 if inside the limits.
`AsinhLocator` Locator for use with the asinh norm, attempting to
space ticks approximately uniformly.
`LogitLocator` Locator for logit scaling.
`AutoMinorLocator` Locator for minor ticks when the axis is linear and the
major ticks are uniformly spaced. Subdivides the major
tick interval into a specified number of minor
intervals, defaulting to 4 or 5 depending on the major
interval.
======================= =======================================================
There are a number of locators specialized for date locations - see
the :mod:`.dates` module.
You can define your own locator by deriving from Locator. You must
override the ``__call__`` method, which returns a sequence of locations,
and you will probably want to override the autoscale method to set the
view limits from the data limits.
If you want to override the default locator, use one of the above or a custom
locator and pass it to the x- or y-axis instance. The relevant methods are::
ax.xaxis.set_major_locator(xmajor_locator)
ax.xaxis.set_minor_locator(xminor_locator)
ax.yaxis.set_major_locator(ymajor_locator)
ax.yaxis.set_minor_locator(yminor_locator)
The default minor locator is `NullLocator`, i.e., no minor ticks on by default.
.. note::
`Locator` instances should not be used with more than one
`~matplotlib.axis.Axis` or `~matplotlib.axes.Axes`. So instead of::
locator = MultipleLocator(5)
ax.xaxis.set_major_locator(locator)
ax2.xaxis.set_major_locator(locator)
do the following instead::
ax.xaxis.set_major_locator(MultipleLocator(5))
ax2.xaxis.set_major_locator(MultipleLocator(5))
.. _formatters:
Tick formatting
---------------
Tick formatting is controlled by classes derived from Formatter. The formatter
operates on a single tick value and returns a string to the axis.
========================= =====================================================
`NullFormatter` No labels on the ticks.
`FixedFormatter` Set the strings manually for the labels.
`FuncFormatter` User defined function sets the labels.
`StrMethodFormatter` Use string `format` method.
`FormatStrFormatter` Use an old-style sprintf format string.
`ScalarFormatter` Default formatter for scalars: autopick the format
string.
`LogFormatter` Formatter for log axes.
`LogFormatterExponent` Format values for log axis using
``exponent = log_base(value)``.
`LogFormatterMathtext` Format values for log axis using
``exponent = log_base(value)`` using Math text.
`LogFormatterSciNotation` Format values for log axis using scientific notation.
`LogitFormatter` Probability formatter.
`EngFormatter` Format labels in engineering notation.
`PercentFormatter` Format labels as a percentage.
========================= =====================================================
You can derive your own formatter from the Formatter base class by
simply overriding the ``__call__`` method. The formatter class has
access to the axis view and data limits.
To control the major and minor tick label formats, use one of the
following methods::
ax.xaxis.set_major_formatter(xmajor_formatter)
ax.xaxis.set_minor_formatter(xminor_formatter)
ax.yaxis.set_major_formatter(ymajor_formatter)
ax.yaxis.set_minor_formatter(yminor_formatter)
In addition to a `.Formatter` instance, `~.Axis.set_major_formatter` and
`~.Axis.set_minor_formatter` also accept a ``str`` or function. ``str`` input
will be internally replaced with an autogenerated `.StrMethodFormatter` with
the input ``str``. For function input, a `.FuncFormatter` with the input
function will be generated and used.
See :doc:`/gallery/ticks/major_minor_demo` for an example of setting major
and minor ticks. See the :mod:`matplotlib.dates` module for more information
and examples of using date locators and formatters.
"""
import itertools
import logging
import locale
import math
from numbers import Integral
import string
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook
from matplotlib import transforms as mtransforms
_log = logging.getLogger(__name__)
__all__ = ('TickHelper', 'Formatter', 'FixedFormatter',
'NullFormatter', 'FuncFormatter', 'FormatStrFormatter',
'StrMethodFormatter', 'ScalarFormatter', 'LogFormatter',
'LogFormatterExponent', 'LogFormatterMathtext',
'LogFormatterSciNotation',
'LogitFormatter', 'EngFormatter', 'PercentFormatter',
'Locator', 'IndexLocator', 'FixedLocator', 'NullLocator',
'LinearLocator', 'LogLocator', 'AutoLocator',
'MultipleLocator', 'MaxNLocator', 'AutoMinorLocator',
'SymmetricalLogLocator', 'AsinhLocator', 'LogitLocator')
class _DummyAxis:
__name__ = "dummy"
def __init__(self, minpos=0):
self._data_interval = (0, 1)
self._view_interval = (0, 1)
self._minpos = minpos
def get_view_interval(self):
return self._view_interval
def set_view_interval(self, vmin, vmax):
self._view_interval = (vmin, vmax)
def get_minpos(self):
return self._minpos
def get_data_interval(self):
return self._data_interval
def set_data_interval(self, vmin, vmax):
self._data_interval = (vmin, vmax)
def get_tick_space(self):
# Just use the long-standing default of nbins==9
return 9
class TickHelper:
axis = None
def set_axis(self, axis):
self.axis = axis
def create_dummy_axis(self, **kwargs):
if self.axis is None:
self.axis = _DummyAxis(**kwargs)
class Formatter(TickHelper):
"""
Create a string based on a tick value and location.
The Formatter provides four formatting methods for different use cases:
- `format_ticks`: The public API for generating tick labels from a set of
tick values.
- `__call__`: The low-level primitive for formatting a single tick value,
potentially in the context of multiple values.
- `format_data`: Context-independent representation of a single value.
Used internally, e.g. for offset and scientific-notation strings.
- `format_data_short`: Concise plain-text representation of a single value
for the interactive mouseover tooltip.
"""
# some classes want to see all the locs to help format
# individual ones
_locs = []
locs = _api.deprecate_privatize_attribute("3.11")
def __call__(self, x, pos=None):
"""
Return the tick label strings for value *x* at tick index *pos*.
This is the low-level formatting primitive for a single tick in
the context of multiple ticks. Any context-dependent state
(e.g. locs, offset, order of magnitude) must already be configured,
typically by a prior call to ``format_ticks`` or ``set_locs``.
*pos* defines the index into ``self.locs`` so that the format can
depend on the location. ``pos=None`` indicates an unspecified
location.
The output may contain mathtext or LaTeX markup.
Subclasses must override this method.
"""
raise NotImplementedError('Derived must override')
def format_ticks(self, values):
"""
Return the tick label strings for all *values*.
This is the public API for generating tick labels. It calls
``set_locs`` to configure context-dependent formatting state before
delegating to ``__call__`` for each individual value.
The output may contain mathtext or LaTeX markup.
Use this method (rather than ``__call__``) whenever formatting a
complete set of tick values, so that formatters which need to see
all tick locations (e.g. to determine precision, offsets, or which
date components to display) can work correctly.
"""
self.set_locs(values)
return [self(value, i) for i, value in enumerate(values)]
def format_data(self, value):
"""
Return the context-independent string representation of a single *value*.
This is used internally, e.g. for constructing offset and
scientific-notation strings. It always formats with ``pos=None``
and should return a context-independent representation
rather than a concise tick label.
The output may contain mathtext or LaTeX markup.
"""
return self.__call__(value)
def format_data_short(self, value):
"""
Return a short string representation of *value* for the mouseover
tooltip (the coordinate display in the interactive figure window).
This should return concise, plain text (no mathtext / LaTeX).
The precision is typically adapted to the current axis resolution
so that neighbouring pixels produce distinguishable labels.
Defaults to `.Formatter.format_data`; subclasses should override
this to provide a plain-text representation that is independent
of the current tick locations.
Note: The mouseover text can be customized by setting the
``Axes.fmt_xdata`` and ``Axes.fmt_ydata`` attributes.
"""
return self.format_data(value)
def get_offset(self):
return ''
def set_locs(self, locs):
"""
Set the locations of the ticks.
This method is called before computing the tick labels because some
formatters need to know all tick locations to do so.
"""
self._locs = locs
@staticmethod
def fix_minus(s):
"""
Some classes may want to replace a hyphen for minus with the proper
Unicode symbol (U+2212) for typographical correctness. This is a
helper method to perform such a replacement when it is enabled via
:rc:`axes.unicode_minus`.
"""
return (s.replace('-', '\N{MINUS SIGN}')
if mpl.rcParams['axes.unicode_minus']
else s)
def _set_locator(self, locator):
"""Subclasses may want to override this to set a locator."""
pass
class NullFormatter(Formatter):
"""Always return the empty string."""
def __call__(self, x, pos=None):
# docstring inherited
return ''
class FixedFormatter(Formatter):
"""
Return fixed strings for tick labels based only on position, not value.
.. note::
`.FixedFormatter` should only be used together with `.FixedLocator`.
Otherwise, the labels may end up in unexpected positions.
"""
def __init__(self, seq):
"""Set the sequence *seq* of strings that will be used for labels."""
self.seq = seq
self.offset_string = ''
def __call__(self, x, pos=None):
"""
Return the label that matches the position, regardless of the value.
For positions ``pos < len(seq)``, return ``seq[i]`` regardless of
*x*. Otherwise return empty string. ``seq`` is the sequence of
strings that this object was initialized with.
"""
if pos is None or pos >= len(self.seq):
return ''
else:
return self.seq[pos]
def get_offset(self):
return self.offset_string
def set_offset_string(self, ofs):
self.offset_string = ofs
class FuncFormatter(Formatter):
"""
Use a user-defined function for formatting.
The function should take in two inputs (a tick value ``x`` and a
position ``pos``), and return a string containing the corresponding
tick label.
"""
def __init__(self, func):
self.func = func
self.offset_string = ""
def __call__(self, x, pos=None):
"""
Return the value of the user defined function.
*x* and *pos* are passed through as-is.
"""
return self.func(x, pos)
def get_offset(self):
return self.offset_string
def set_offset_string(self, ofs):
self.offset_string = ofs
class FormatStrFormatter(Formatter):
"""
Use an old-style ('%' operator) format string to format the tick.
The format string should have a single variable format (%) in it.
It will be applied to the value (not the position) of the tick.
Negative numeric values (e.g., -1) will use a dash, not a Unicode minus;
use mathtext to get a Unicode minus by wrapping the format specifier with $
(e.g. "$%g$").
"""
def __init__(self, fmt):
self.fmt = fmt
def __call__(self, x, pos=None):
"""
Return the formatted label string.
Only the value *x* is formatted. The position is ignored.
"""
return self.fmt % x
class _UnicodeMinusFormat(string.Formatter):
"""
A specialized string formatter so that `.StrMethodFormatter` respects
:rc:`axes.unicode_minus`. This implementation relies on the fact that the
format string is only ever called with kwargs *x* and *pos*, so it blindly
replaces dashes by unicode minuses without further checking.
"""
def format_field(self, value, format_spec):
return Formatter.fix_minus(super().format_field(value, format_spec))
class StrMethodFormatter(Formatter):
"""
Use a new-style format string (as used by `str.format`) to format the tick.
The field used for the tick value must be labeled *x* and the field used
for the tick position must be labeled *pos*.
The formatter will respect :rc:`axes.unicode_minus` when formatting
negative numeric values.
It is typically unnecessary to explicitly construct `.StrMethodFormatter`
objects, as `~.Axis.set_major_formatter` directly accepts the format string
itself.
Examples
--------
>>> formatter = StrMethodFormatter("{x} km")
>>> formatter(10)
"10 km"
"""
def __init__(self, fmt):
self.fmt = fmt
def __call__(self, x, pos=None):
"""
Return the formatted label string.
*x* and *pos* are passed to `str.format` as keyword arguments
with those exact names.
"""
return _UnicodeMinusFormat().format(self.fmt, x=x, pos=pos)
class ScalarFormatter(Formatter):
"""
Format tick values as a number.
Parameters
----------
useOffset : bool or float, default: :rc:`axes.formatter.useoffset`
Whether to use offset notation. See `.set_useOffset`.
useMathText : bool, default: :rc:`axes.formatter.use_mathtext`
Whether to use fancy math formatting. See `.set_useMathText`.
useLocale : bool, default: :rc:`axes.formatter.use_locale`.
Whether to use locale settings for decimal sign and positive sign.
See `.set_useLocale`.
usetex : bool, default: :rc:`text.usetex`
To enable/disable the use of TeX's math mode for rendering the
numbers in the formatter.
.. versionadded:: 3.10
Notes
-----
In addition to the parameters above, the formatting of scientific vs.
floating point representation can be configured via `.set_scientific`
and `.set_powerlimits`).
**Offset notation and scientific notation**
Offset notation and scientific notation look quite similar at first sight.
Both split some information from the formatted tick values and display it
at the end of the axis.
- The scientific notation splits up the order of magnitude, i.e. a
multiplicative scaling factor, e.g. ``1e6``.
- The offset notation separates an additive constant, e.g. ``+1e6``. The
offset notation label is always prefixed with a ``+`` or ``-`` sign
and is thus distinguishable from the order of magnitude label.
The following plot with x limits ``1_000_000`` to ``1_000_010`` illustrates
the different formatting. Note the labels at the right edge of the x axis.
.. plot::
lim = (1_000_000, 1_000_010)
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, gridspec_kw={'hspace': 2})
ax1.set(title='offset notation', xlim=lim)
ax2.set(title='scientific notation', xlim=lim)
ax2.xaxis.get_major_formatter().set_useOffset(False)
ax3.set(title='floating-point notation', xlim=lim)
ax3.xaxis.get_major_formatter().set_useOffset(False)
ax3.xaxis.get_major_formatter().set_scientific(False)
"""
orderOfMagnitude = _api.deprecate_privatize_attribute("3.11")
format = _api.deprecate_privatize_attribute("3.11")
def __init__(self, useOffset=None, useMathText=None, useLocale=None, *,
usetex=None):
useOffset = mpl._val_or_rc(useOffset, 'axes.formatter.useoffset')
self._offset_threshold = mpl.rcParams['axes.formatter.offset_threshold']
self.set_useOffset(useOffset)
self.set_usetex(usetex)
self.set_useMathText(useMathText)
self._orderOfMagnitude = 0
self._format = ''
self._scientific = True
self._powerlimits = mpl.rcParams['axes.formatter.limits']
self.set_useLocale(useLocale)
def get_usetex(self):
"""Return whether TeX's math mode is enabled for rendering."""
return self._usetex
def set_usetex(self, val):
"""Set whether to use TeX's math mode for rendering numbers in the formatter."""
self._usetex = mpl._val_or_rc(val, 'text.usetex')
usetex = property(fget=get_usetex, fset=set_usetex)
def get_useOffset(self):
"""
Return whether automatic mode for offset notation is active.
This returns True if ``set_useOffset(True)``; it returns False if an
explicit offset was set, e.g. ``set_useOffset(1000)``.
See Also
--------
ScalarFormatter.set_useOffset
"""
return self._useOffset
def set_useOffset(self, val):
"""
Set whether to use offset notation.
When formatting a set numbers whose value is large compared to their
range, the formatter can separate an additive constant. This can
shorten the formatted numbers so that they are less likely to overlap
when drawn on an axis.
Parameters
----------
val : bool or float
- If False, do not use offset notation.
- If True (=automatic mode), use offset notation if it can make
the residual numbers significantly shorter. The exact behavior
is controlled by :rc:`axes.formatter.offset_threshold`.
- If a number, force an offset of the given value.
Examples
--------
With active offset notation, the values
``100_000, 100_002, 100_004, 100_006, 100_008``
will be formatted as ``0, 2, 4, 6, 8`` plus an offset ``+1e5``, which
is written to the edge of the axis.
"""
if isinstance(val, bool):
self.offset = 0
self._useOffset = val
else:
self._useOffset = False
self.offset = val
useOffset = property(fget=get_useOffset, fset=set_useOffset)
def get_useLocale(self):
"""
Return whether locale settings are used for formatting.
See Also
--------
ScalarFormatter.set_useLocale
"""
return self._useLocale
def set_useLocale(self, val):
"""
Set whether to use locale settings for decimal sign and positive sign.
Parameters
----------
val : bool or None
*None* resets to :rc:`axes.formatter.use_locale`.
"""
self._useLocale = mpl._val_or_rc(val, 'axes.formatter.use_locale')
useLocale = property(fget=get_useLocale, fset=set_useLocale)
def _format_maybe_minus_and_locale(self, fmt, arg):
"""
Format *arg* with *fmt*, applying Unicode minus and locale if desired.
"""
return self.fix_minus(
# Escape commas introduced by locale.format_string if using math text,
# but not those present from the beginning in fmt.
(",".join(locale.format_string(part, (arg,), True).replace(",", "{,}")
for part in fmt.split(",")) if self._useMathText
else locale.format_string(fmt, (arg,), True))
if self._useLocale
else fmt % arg)
def get_useMathText(self):
"""
Return whether to use fancy math formatting.
See Also
--------
ScalarFormatter.set_useMathText
"""
return self._useMathText
def set_useMathText(self, val):
r"""
Set whether to use fancy math formatting.
If active, scientific notation is formatted as :math:`1.2 \times 10^3`.
Parameters
----------
val : bool or None
*None* resets to :rc:`axes.formatter.use_mathtext`.
"""
if val is None:
self._useMathText = mpl.rcParams['axes.formatter.use_mathtext']
if self._useMathText is False:
try:
from matplotlib import font_manager
ufont = font_manager.findfont(
font_manager.FontProperties(
family=mpl.rcParams["font.family"]
),
fallback_to_default=False,
)
except ValueError:
ufont = None
if ufont == str(cbook._get_data_path("fonts/ttf/cmr10.ttf")):
_api.warn_external(
"cmr10 font should ideally be used with "
"mathtext, set axes.formatter.use_mathtext to True"
)
else:
self._useMathText = val
useMathText = property(fget=get_useMathText, fset=set_useMathText)
def __call__(self, x, pos=None):
"""
Return the format for tick value *x* at position *pos*.
"""
if len(self._locs) == 0:
return ''
else:
xp = (x - self.offset) / (10. ** self._orderOfMagnitude)
if abs(xp) < 1e-8:
xp = 0
return self._format_maybe_minus_and_locale(self._format, xp)
def set_scientific(self, b):
"""
Turn scientific notation on or off.
See Also
--------
ScalarFormatter.set_powerlimits
"""
self._scientific = bool(b)
def set_powerlimits(self, lims):
r"""
Set size thresholds for scientific notation.
Parameters
----------
lims : (int, int)
A tuple *(min_exp, max_exp)* containing the powers of 10 that
determine the switchover threshold. For a number representable as
:math:`a \times 10^\mathrm{exp}` with :math:`1 1/2, with x = 1 - v, indicate if x should be displayed as
$\overline{v}$. The default is to display $1 - v$.
one_half : str, default: r"\\frac{1}{2}"
The string used to represent 1/2.
minor : bool, default: False
Indicate if the formatter is formatting minor ticks or not.
Basically minor ticks are not labelled, except when only few ticks
are provided, ticks with most space with neighbor ticks are
labelled. See other parameters to change the default behavior.
minor_threshold : int, default: 25
Maximum number of locs for labelling some minor ticks. This
parameter have no effect if minor is False.
minor_number : int, default: 6
Number of ticks which are labelled when the number of ticks is
below the threshold.
"""
self._use_overline = use_overline
self._one_half = one_half
self._minor = minor
self._labelled = set()
self._minor_threshold = minor_threshold
self._minor_number = minor_number
def use_overline(self, use_overline):
r"""
Switch display mode with overline for labelling p>1/2.
Parameters
----------
use_overline : bool
If x > 1/2, with x = 1 - v, indicate if x should be displayed as
$\overline{v}$. The default is to display $1 - v$.
"""
self._use_overline = use_overline
def set_one_half(self, one_half):
r"""
Set the way one half is displayed.
one_half : str
The string used to represent 1/2.
"""
self._one_half = one_half
def set_minor_threshold(self, minor_threshold):
"""
Set the threshold for labelling minors ticks.
Parameters
----------
minor_threshold : int
Maximum number of locations for labelling some minor ticks. This
parameter have no effect if minor is False.
"""
self._minor_threshold = minor_threshold
def set_minor_number(self, minor_number):
"""
Set the number of minor ticks to label when some minor ticks are
labelled.
Parameters
----------
minor_number : int
Number of ticks which are labelled when the number of ticks is
below the threshold.
"""
self._minor_number = minor_number
def set_locs(self, locs):
self._locs = np.array(locs)
self._labelled.clear()
if not self._minor:
return None
if all(
_is_decade(x, rtol=1e-7)
or _is_decade(1 - x, rtol=1e-7)
or (_is_close_to_int(2 * x) and
int(np.round(2 * x)) == 1)
for x in locs
):
# minor ticks are subsample from ideal, so no label
return None
if len(locs) < self._minor_threshold:
if len(locs) < self._minor_number:
self._labelled.update(locs)
else:
# we do not have a lot of minor ticks, so only few decades are
# displayed, then we choose some (spaced) minor ticks to label.
# Only minor ticks are known, we assume it is sufficient to
# choice which ticks are displayed.
# For each ticks we compute the distance between the ticks and
# the previous, and between the ticks and the next one. Ticks
# with smallest minimum are chosen. As tiebreak, the ticks
# with smallest sum is chosen.
diff = np.diff(-np.log(1 / self._locs - 1))
space_pessimistic = np.minimum(
np.concatenate(((np.inf,), diff)),
np.concatenate((diff, (np.inf,))),
)
space_sum = (
np.concatenate(((0,), diff))
+ np.concatenate((diff, (0,)))
)
good_minor = sorted(
range(len(self._locs)),
key=lambda i: (space_pessimistic[i], space_sum[i]),
)[-self._minor_number:]
self._labelled.update(locs[i] for i in good_minor)
def _format_value(self, x, locs, sci_notation=True):
if sci_notation:
exponent = math.floor(np.log10(x))
min_precision = 0
else:
exponent = 0
min_precision = 1
value = x * 10 ** (-exponent)
if len(locs) < 2:
precision = min_precision
else:
diff = np.sort(np.abs(locs - x))[1]
precision = -np.log10(diff) + exponent
precision = (
int(np.round(precision))
if _is_close_to_int(precision)
else math.ceil(precision)
)
if precision < min_precision:
precision = min_precision
mantissa = r"%.*f" % (precision, value)
if not sci_notation:
return mantissa
s = r"%s\cdot10^{%d}" % (mantissa, exponent)
return s
def _one_minus(self, s):
if self._use_overline:
return r"\overline{%s}" % s
else:
return f"1-{s}"
def __call__(self, x, pos=None):
if self._minor and x not in self._labelled:
return ""
if x = 1:
return ""
if _is_close_to_int(2 * x) and round(2 * x) == 1:
s = self._one_half
elif x < 0.5 and _is_decade(x, rtol=1e-7):
exponent = round(math.log10(x))
s = "10^{%d}" % exponent
elif x > 0.5 and _is_decade(1 - x, rtol=1e-7):
exponent = round(math.log10(1 - x))
s = self._one_minus("10^{%d}" % exponent)
elif x < 0.1:
s = self._format_value(x, self._locs)
elif x > 0.9:
s = self._one_minus(self._format_value(1-x, 1-self._locs))
else:
s = self._format_value(x, self._locs, sci_notation=False)
return r"$\mathdefault{%s}$" % s
def format_data_short(self, value):
# docstring inherited
# Thresholds chosen to use scientific notation iff exponent 0:
vmin, vmax = sorted(self.axis.get_view_interval())
if self._useOffset:
self._compute_offset()
if self.offset != 0:
# We don't want to use the offset computed by
# self._compute_offset because it rounds the offset unaware
# of our engineering prefixes preference, and this can
# cause ticks with 4+ digits to appear. These ticks are
# slightly less readable, so if offset is justified
# (decided by self._compute_offset) we set it to better
# value:
self.offset = round((vmin + vmax)/2, 3)
# Use log1000 to use engineers' oom standards
self._orderOfMagnitude = math.floor(math.log(vmax - vmin, 1000))*3
self._set_format()
# Simplify a bit ScalarFormatter.get_offset: We always want to use
# self.format_data. Also we want to return a non-empty string only if there
# is an offset, no matter what is self._orderOfMagnitude. If there _is_ an
# offset, self._orderOfMagnitude is consulted. This behavior is verified
# in `test_ticker.py`.
def get_offset(self):
# docstring inherited
if len(self._locs) == 0:
return ''
if self.offset:
offsetStr = ''
if self.offset:
offsetStr = self.format_data(self.offset)
if self.offset > 0:
offsetStr = '+' + offsetStr
sciNotStr = self.format_data(10 ** self._orderOfMagnitude)
if self._useMathText or self._usetex:
if sciNotStr != '':
sciNotStr = r'\times%s' % sciNotStr
s = f'${sciNotStr}{offsetStr}$'
else:
s = sciNotStr + offsetStr
return self.fix_minus(s)
return ''
def format_eng(self, num):
"""Alias to EngFormatter.format_data"""
return self.format_data(num)
def format_data(self, value):
"""
Format a number in engineering notation, appending a letter
representing the power of 1000 of the original number.
Some examples:
>>> format_data(0) # for self.places = 0
'0'
>>> format_data(1000000) # for self.places = 1
'1.0 M'
>>> format_data(-1e-6) # for self.places = 2
'-1.00 \N{MICRO SIGN}'
"""
sign = 1
fmt = "g" if self.places is None else f".{self.places:d}f"
if value < 0:
sign = -1
value = -value
if value != 0:
pow10 = int(math.floor(math.log10(value) / 3) * 3)
else:
pow10 = 0
# Force value to zero, to avoid inconsistencies like
# format_eng(-0) = "0" and format_eng(0.0) = "0"
# but format_eng(-0.0) = "-0.0"
value = 0.0
pow10 = np.clip(pow10, min(self.ENG_PREFIXES), max(self.ENG_PREFIXES))
mant = sign * value / (10.0 ** pow10)
# Taking care of the cases like 999.9..., which may be rounded to 1000
# instead of 1 k. Beware of the corner case of values that are beyond
# the range of SI prefixes (i.e. > 'Y').
if (abs(float(format(mant, fmt))) >= 1000
and pow10 < max(self.ENG_PREFIXES)):
mant /= 1000
pow10 += 3
unit_prefix = self.ENG_PREFIXES[int(pow10)]
if self.unit or unit_prefix:
suffix = f"{self.sep}{unit_prefix}{self.unit}"
else:
suffix = ""
if self._usetex or self._useMathText:
return f"${mant:{fmt}}${suffix}"
else:
return f"{mant:{fmt}}{suffix}"
class PercentFormatter(Formatter):
"""
Format numbers as a percentage.
Parameters
----------
xmax : float
Determines how the number is converted into a percentage.
*xmax* is the data value that corresponds to 100%.
Percentages are computed as ``x / xmax * 100``. So if the data is
already scaled to be percentages, *xmax* will be 100. Another common
situation is where *xmax* is 1.0.
decimals : None or int
The number of decimal places to place after the point.
If *None* (the default), the number will be computed automatically.
symbol : str or None
A string that will be appended to the label. It may be
*None* or empty to indicate that no symbol should be used. LaTeX
special characters are escaped in *symbol* whenever latex mode is
enabled, unless *is_latex* is *True*.
is_latex : bool
If *False*, reserved LaTeX characters in *symbol* will be escaped.
"""
def __init__(self, xmax=100, decimals=None, symbol='%', is_latex=False):
self.xmax = xmax + 0.0
self.decimals = decimals
self._symbol = symbol
self._is_latex = is_latex
def __call__(self, x, pos=None):
"""Format the tick as a percentage with the appropriate scaling."""
ax_min, ax_max = self.axis.get_view_interval()
display_range = abs(ax_max - ax_min)
return self.fix_minus(self.format_pct(x, display_range))
def format_pct(self, x, display_range):
"""
Format the number as a percentage number with the correct
number of decimals and adds the percent symbol, if any.
If ``self.decimals`` is `None`, the number of digits after the
decimal point is set based on the *display_range* of the axis
as follows:
============= ======== =======================
display_range decimals sample
============= ======== =======================
>50 0 ``x = 34.5`` => 35%
>5 1 ``x = 34.5`` => 34.5%
>0.5 2 ``x = 34.5`` => 34.50%
... ... ...
============= ======== =======================
This method will not be very good for tiny axis ranges or
extremely large ones. It assumes that the values on the chart
are percentages displayed on a reasonable scale.
"""
x = self.convert_to_pct(x)
if self.decimals is None:
# conversion works because display_range is a difference
scaled_range = self.convert_to_pct(display_range)
if scaled_range