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
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.
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 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:
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:
In addition to a Formatter instance, set_major_formatter and
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 with the input
function will be generated and used.
See Major and minor ticks for an example of setting major
and minor ticks. See the matplotlib.dates module for more information
and examples of using date locators and formatters.
The scale parameter defining the extent
of the quasi-linear region.
numticks : int, default: 11
The approximate number of major ticks that will fit
along the entire axis
symthresh : float, default: 0.2
The fractional threshold beneath which data which covers
a range that is approximately symmetric about zero
will have ticks that are exactly symmetric.
base : int, default: 10
The number base used for rounding tick locations
on a logarithmic scale. If this is less than one,
then rounding is to the nearest integer multiple
of powers of ten.
subs : tuple, default: None
Multiples of the number base, typically used
for the minor ticks, e.g. (2, 5) when base=10.
The number of subdivisions of the interval between major ticks;
e.g., n=2 will place a single minor tick midway between major ticks.
If n is 'auto', it will be set to 4 or 5: if the distance
between the major ticks equals 1, 2.5, 5 or 10 it can be perfectly
divided in 5 equidistant sub-intervals with a length multiple of
0.05; otherwise, it is divided in 4 sub-intervals.
__call__()
Return the locations of the ticks.
tick_values(vmin, vmax)
Return the values of the located ticks given vmin and vmax.
Format axis values using engineering prefixes to represent powers
of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7.
Parameters:
unit : str, default: ""
Unit symbol to use, suitable for use with single-letter
representations of powers of 1000. For example, 'Hz' or 'm'.
places : int, default: None
Precision with which to display the number, specified in
digits after the decimal point (there will be between one
and three digits before the decimal point). If it is None,
the formatting falls back to the floating point format '%g',
which displays up to 6 significant digits, i.e. the equivalent
value for places varies between 0 and 5 (inclusive).
sep : str, default: " "
Separator used between the value and the prefix/unit. For
example, one get '3.14 mV' if sep is " " (default) and
'3.14mV' if sep is "". Besides the default behavior, some
other useful options may be:
Return fixed strings for tick labels based only on position, not value.
Set the sequence seq of strings that will be used for labels.
__call__(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 nbins is None ticks are placed at all values. Otherwise, the locs array of
possible positions will be subsampled to keep the number of ticks
≤nbins+1. The subsampling will be done to include the smallest
absolute value; for example, if zero is included in the array of possibilities, then
it will be included in the chosen ticks.
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$").
__call__(x, pos=None)
Return the formatted label string.
Only the value x is formatted. The position is ignored.
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.
__call__(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.
staticfix_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
rcParams["axes.unicode_minus"] (default: True).
format_data(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.
format_data_short(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.
format_ticks(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.
get_offset()
propertylocs
[Deprecated]
Notes
set_locs(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.
The first time this function is called, it will try to set the number of
ticks to make a nice tick partitioning. Thereafter, the number of ticks
will be fixed to avoid jumping during interactive navigation.
Parameters:
numticks : int or None, default None
Number of ticks. If None, numticks = 11.
presets : dict or None, default: None
Dictionary mapping (vmin,vmax) to an array of locations.
Overrides numticks if there is an entry for the current
(vmin,vmax).
__call__()
Return the locations of the ticks.
propertynumticks
set_params(numticks=None, presets=None)
Set parameters within this locator.
tick_values(vmin, vmax)
Return the values of the located ticks given vmin and vmax.
This is intended to be called immediately before returning locs from
__call__ to inform users in case their Locator returns a huge
number of ticks, causing Matplotlib to run out of memory.
The "strange" name of this method dates back to when it would raise an
exception instead of emitting a log.
set_params(**kwargs)
Do nothing, and raise a warning. Any locator class not supporting the
set_params() function will call this.
tick_values(vmin, vmax)
Return the values of the located ticks given vmin and vmax.
view_limits(vmin, vmax)
Select a scale for the range from vmin to vmax.
Subclasses should override this method to change locator behaviour.
If labelOnlyBase is False, these two numbers control
the labeling of ticks that are not at integer powers of
base; normally these are the minor ticks.
The first number (subset) is the largest number of major ticks for
which minor ticks are labeled; e.g., the default, 1, means that minor
ticks are labeled as long as there is no more than 1 major tick. (It
is assumed that major ticks are at integer powers of base.)
The second number (all) is a threshold, in log-units of the axis
limit range, over which only a subset of the minor ticks are labeled,
so as to avoid crowding; e.g., with the default value (0.4) and the
usual base=10, all minor ticks are shown only if the axis limit
range spans less than 0.4 decades.
linthresh : None or float, default: None
If a symmetric log scale is in use, its linthresh
parameter must be supplied here.
Notes
The set_locs method must be called to enable the subsetting
logic controlled by the minor_thresholds parameter.
In some cases such as the colorbar, there is no distinction between
major and minor ticks; the tick locations might be set manually,
or by a locator that puts ticks at integer powers of base and
at intermediate locations. For this situation, disable the
minor_thresholds logic by using minor_thresholds=(np.inf,np.inf),
so that all ticks will be labeled.
To disable labeling of minor ticks when 'labelOnlyBase' is False,
use minor_thresholds=(0,0). This is the default for the
"classic" style.
Examples
To label a subset of minor ticks when there are up to 2 major ticks,
and all of the ticks when zoomed in to 0.5 decades or less, use
minor_thresholds=(2,0.5).
__call__(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.
format_data(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.
format_data_short(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.
set_base(base)
Change the base for labeling.
set_label_minor(labelOnlyBase)
Switch minor tick labeling on or off.
Parameters:
labelOnlyBase : bool
If True, label ticks only at integer powers of base.
set_locs(locs=None)
Use axis view limits to control which ticks are labeled.
The locs parameter is ignored in the present algorithm.
Format values for log axis using exponent=log_base(value).
__call__(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 base of the log used, so major ticks are placed at base**n, where
n is an integer.
subs : None or {'auto', 'all'} or sequence of float, default: (1.0,)
Gives the multiples of integer powers of the base at which to place ticks.
The default of (1.0,) places ticks only at integer powers of the base.
Permitted string values are 'auto' and 'all'. Both of these use an
algorithm based on the axis view limits to determine whether and how to put
ticks between integer powers of the base:
- 'auto': Ticks are placed only between integer powers.
- 'all': Ticks are placed between at integer powers.
- : Equivalent to .
__call__()
Return the locations of the ticks.
nonsingular(vmin, vmax)
Adjust a range as needed to avoid singularities.
This method gets called during autoscaling, with (v0,v1) set to
the data limits on the Axes if the Axes contains any data, or
(-inf,+inf) if not.
If v0==v1 (possibly up to some floating point slop), this
method returns an expanded interval around this value.
If (v0,v1)==(-inf,+inf), this method returns appropriate
default view limits.
If x > 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.
__call__(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.
format_data_short(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.
set_locs(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.
set_minor_number(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.
set_minor_threshold(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.
set_one_half(one_half)
Set the way one half is displayed.
one_half : str
The string used to represent 1/2.
use_overline(use_overline)
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$.
Place evenly spaced ticks, with a cap on the total number of ticks.
Finds nice tick locations with no more than nbins+1 ticks being within the
view limits. Locations beyond the limits are added to support autoscaling.
Parameters:
nbins : int or 'auto', default: 10
Maximum number of intervals; one less than max number of
ticks. If the string 'auto', the number of bins will be
automatically determined based on the length of the axis.
steps : array-like, optional
Sequence of acceptable tick multiples, starting with 1 and
ending with 10. For example, if steps=[1,2,4,5,10],
20,40,60 or 0.4,0.6,0.8 would be possible
sets of ticks because they are multiples of 2.
30,60,90 would not be generated because 3 does not
appear in this example list of steps.
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.
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.
__call__(x, pos=None)
Format the tick as a percentage with the appropriate scaling.
convert_to_pct(x)
format_pct(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
propertysymbol
The configured percent symbol as a string.
If LaTeX is enabled via rcParams["text.usetex"] (default: False), the special characters
{'#','$','%','&','~','_','^','\','{','}'} are
automatically escaped in the string.
To enable/disable the use of TeX's math mode for rendering the
numbers in the formatter.
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.
Return the format for tick value x at position pos.
propertyformat
[Deprecated]
Notes
format_data(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.
format_data_short(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.
get_offset()
Return scientific notation, plus offset.
get_useLocale()
Return whether locale settings are used for formatting.
get_useMathText()
Return whether to use fancy math formatting.
get_useOffset()
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).
get_usetex()
Return whether TeX's math mode is enabled for rendering.
propertyorderOfMagnitude
[Deprecated]
Notes
set_locs(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.
set_powerlimits(lims)
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
a×10exp with ,
scientific notation will be used if or
.
set_scientific(b)
Turn scientific notation on or off.
set_useLocale(val)
Set whether to use locale settings for decimal sign and positive sign.
If active, scientific notation is formatted as 1.2×103.
Parameters:
val : bool or None
None resets to (default: ).
set_useOffset(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 rcParams["axes.formatter.offset_threshold"] (default: ).
set_usetex(val)
Set whether to use TeX's math mode for rendering numbers in the formatter.
propertyuseLocale
Return whether locale settings are used for formatting.
propertyuseMathText
Return whether to use fancy math formatting.
propertyuseOffset
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).
propertyusetex
Return whether TeX's math mode is enabled for rendering.
To enable/disable the use mathtext for rendering the numbers in
the formatter.
useOffset : bool or float, default: False
Whether to use offset notation with 103∗N based prefixes.
This features allows showing an offset with standard SI order of
magnitude prefix near the axis. Offset is computed similarly to
how ScalarFormatter computes it internally, but here you are
guaranteed to get an offset which will make the tick labels exceed
3 digits. See also set_useOffset.
>>> format_data(-1e-6)# for self.places = 2'-1.00 µ'
>>>
print
(
loc
())
[1, 2, 3, 4]
>>>
print
(
loc
())
[1, 2, 3, 4]
(v0,
v1)
>>>
print
(
loc
())
[1, 2, 3, 4]
and
None
'auto'
numticks : None or int, default: None
The maximum number of ticks to allow on a given axis. The default of
None will try to choose intelligently as long as this Locator has
already been assigned to an axis using get_tick_space, but
otherwise falls back to 9.
(v0,
v1)
>>>
print
(
loc
())
[1, 2, 3, 4]
(v0,
v1)
>>>
print
(
loc
())
[1, 2, 3, 4]
If True, ticks will take only integer values, provided at least
min_n_ticks integers are found within the view limits.
symmetric : bool, default: False
If True, autoscaling will result in a range symmetric about zero.
Remove the 'lower' tick, the 'upper' tick, or ticks on 'both' sides
if they fall exactly on an axis' edge (this typically occurs when
rcParams["axes.autolimit_mode"] (default: 'data') is 'round_numbers'). Removing such ticks
is mostly useful for stacked or ganged plots, where the upper tick
of an Axes overlaps with the lower tick of the axes above it.
min_n_ticks : int, default: 2
Relax nbins and integer constraints if necessary to obtain
this minimum number of ticks.
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.