matplotlib.ticker
¶This module contains classes to support completely configurable tick locating and formatting. 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. Generic tick locators and formatters are provided, as well as domain specific custom ones.
The default formatter identifies when the xdata being plotted is a small range on top of a large offset. To reduce the chances that the ticklabels overlap, the ticks are labeled as deltas from a fixed offset. For example:
ax.plot(np.arange(2000, 2010), range(10))
will have tick of 09 with an offset of +2e3. If this is not desired turn off the use of the offset on the default formatter:
ax.get_xaxis().get_major_formatter().set_useOffset(False)
set the rcParam axes.formatter.useoffset=False
to turn it off
globally, or set a different formatter.
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 semiautomatic 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
LinearLocator
LogLocator
MultipleLocator
FixedLocator
IndexLocator
x = range(len(y))
).NullLocator
SymmetricalLogLocator
LogLocator
for the
part outside of the threshold and adds 0 if inside the limits.LogitLocator
OldAutoLocator
MultipleLocator
and dynamically reassign it for intelligent
ticking during navigation.AutoMinorLocator
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:
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.
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
IndexFormatter
FixedFormatter
FuncFormatter
StrMethodFormatter
format
method.FormatStrFormatter
ScalarFormatter
LogFormatter
LogFormatterExponent
exponent = log_base(value)
.LogFormatterMathtext
exponent = log_base(value)
using Math text.LogFormatterSciNotation
LogitFormatter
EngFormatter
PercentFormatter
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)
See Major Minor Demo 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.
matplotlib.ticker.
Formatter
[source]¶Bases: matplotlib.ticker.TickHelper
Create a string based on a tick value and location.
fix_minus
(s)[source]¶Some classes may want to replace a hyphen for minus with the proper unicode symbol (U+2212) for typographical correctness. The default is to not replace it.
Note, if you use this method, e.g., in format_data()
or
call, you probably don't want to use it for
format_data_short()
since the toolbar uses this for
interactive coord reporting and I doubt we can expect GUIs
across platforms will handle the unicode correctly. So for
now the classes that override fix_minus()
should have an
explicit format_data_short()
method
format_data
(value)[source]¶Returns the full string representation of the value with the position unspecified.
format_data_short
(value)[source]¶Return a short string version of the tick value.
Defaults to the positionindependent long value.
locs
= []¶matplotlib.ticker.
FixedFormatter
(seq)[source]¶Bases: matplotlib.ticker.Formatter
Return fixed strings for tick labels based only on position, not value.
Set the sequence of strings that will be used for labels.
matplotlib.ticker.
NullFormatter
[source]¶Bases: matplotlib.ticker.Formatter
Always return the empty string.
matplotlib.ticker.
FuncFormatter
(func)[source]¶Bases: matplotlib.ticker.Formatter
Use a userdefined 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.
matplotlib.ticker.
FormatStrFormatter
(fmt)[source]¶Bases: matplotlib.ticker.Formatter
Use an oldstyle ('%' 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.
matplotlib.ticker.
StrMethodFormatter
(fmt)[source]¶Bases: matplotlib.ticker.Formatter
Use a newstyle format string (as used by str.format()
)
to format the tick.
The field used for the value must be labeled x
and the field used
for the position must be labeled pos
.
matplotlib.ticker.
ScalarFormatter
(useOffset=None, useMathText=None, useLocale=None)[source]¶Bases: matplotlib.ticker.Formatter
Format tick values as a number.
Tick value is interpreted as a plain old number. If
useOffset==True
and the data range is much smaller than the data
average, then an offset will be determined such that the tick labels
are meaningful. Scientific notation is used for data < 10^n
or
data >= 10^m
, where n
and m
are the power limits set
using set_powerlimits((n,m))
. The defaults for these are
controlled by the axes.formatter.limits
rc parameter.
set_powerlimits
(lims)[source]¶Sets size thresholds for scientific notation.
Parameters: 


set_scientific
(b)[source]¶Turn scientific notation on or off.
See also
Method set_powerlimits()
useLocale
¶useMathText
¶useOffset
¶matplotlib.ticker.
LogFormatter
(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source]¶Bases: matplotlib.ticker.Formatter
Base class for formatting ticks on a log or symlog scale.
It may be instantiated directly, or subclassed.
Parameters: 


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 the view limits span up
to 2 decades, and all of the ticks when zoomed in to 0.5 decades
or less, use minor_thresholds=(2, 0.5)
.
To label all minor ticks when the view limits span up to 1.5
decades, use minor_thresholds=(1.5, 1.5)
.
base
(base)[source]¶Change the base for labeling.
Warning
Should always match the base used for LogLocator
format_data
(value)[source]¶Returns the full string representation of the value with the position unspecified.
matplotlib.ticker.
LogFormatterExponent
(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source]¶Bases: matplotlib.ticker.LogFormatter
Format values for log axis using exponent = log_base(value)
.
matplotlib.ticker.
LogFormatterMathtext
(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source]¶Bases: matplotlib.ticker.LogFormatter
Format values for log axis using exponent = log_base(value)
.
matplotlib.ticker.
IndexFormatter
(labels)[source]¶Bases: matplotlib.ticker.Formatter
Format the position x to the nearest ith label where i=int(x+0.5)
matplotlib.ticker.
LogFormatterSciNotation
(base=10.0, labelOnlyBase=False, minor_thresholds=None, linthresh=None)[source]¶Bases: matplotlib.ticker.LogFormatterMathtext
Format values following scientific notation in a logarithmic axis.
matplotlib.ticker.
LogitFormatter
[source]¶Bases: matplotlib.ticker.Formatter
Probability formatter (using Math text).
matplotlib.ticker.
EngFormatter
(unit='', places=None, sep=' ')[source]¶Bases: matplotlib.ticker.Formatter
Formats axis values using engineering prefixes to represent powers of 1000, plus a specified unit, e.g., 10 MHz instead of 1e7.
Parameters: 


ENG_PREFIXES
= {24: 'y', 21: 'z', 18: 'a', 15: 'f', 12: 'p', 9: 'n', 6: 'μ', 3: 'm', 0: '', 3: 'k', 6: 'M', 9: 'G', 12: 'T', 15: 'P', 18: 'E', 21: 'Z', 24: 'Y'}¶format_eng
(num)[source]¶Formats a number in engineering notation, appending a letter representing the power of 1000 of the original number. Some examples:
>>> format_eng(0) # for self.places = 0
'0'
>>> format_eng(1000000) # for self.places = 1
'1.0 M'
>>> format_eng("1e6") # for self.places = 2
'1.00 μ'
matplotlib.ticker.
PercentFormatter
(xmax=100, decimals=None, symbol='%', is_latex=False)[source]¶Bases: matplotlib.ticker.Formatter
Format numbers as a percentage.
Parameters: 


format_pct
(x, display_range)[source]¶Formats 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.
symbol
¶The configured percent symbol as a string.
If LaTeX is enabled via rcParams["text.usetex"]
, the special characters
{'#', '$', '%', '&', '~', '_', '^', '\', '{', '}'}
are
automatically escaped in the string.
matplotlib.ticker.
Locator
[source]¶Bases: matplotlib.ticker.TickHelper
Determine the tick locations;
Note, you should not use the same locator between different
Axis
because the locator stores references to
the Axis data and view limits
MAXTICKS
= 1000¶raise_if_exceeds
(locs)[source]¶raise a RuntimeError if Locator attempts to create more than MAXTICKS locs
set_params
(**kwargs)[source]¶Do nothing, and rase a warning. Any locator class not supporting the set_params() function will call this.
tick_values
(vmin, vmax)[source]¶Return the values of the located ticks given vmin and vmax.
Note
To get tick locations with the vmin and vmax values defined
automatically for the associated axis
simply call
the Locator instance:
>>> print(type(loc))
<type 'Locator'>
>>> print(loc())
[1, 2, 3, 4]
matplotlib.ticker.
IndexLocator
(base, offset)[source]¶Bases: matplotlib.ticker.Locator
Place a tick on every multiple of some base number of points plotted, e.g., on every 5th point. It is assumed that you are doing index plotting; i.e., the axis is 0, len(data). This is mainly useful for x ticks.
place ticks on the ith data points where (ioffset)%base==0
matplotlib.ticker.
FixedLocator
(locs, nbins=None)[source]¶Bases: matplotlib.ticker.Locator
Tick locations are fixed. If nbins is not None, the array of possible positions will be subsampled to keep the number of ticks <= nbins +1. The subsampling will be done so as to include the smallest absolute value; for example, if zero is included in the array of possibilities, then it is guaranteed to be one of the chosen ticks.
matplotlib.ticker.
NullLocator
[source]¶Bases: matplotlib.ticker.Locator
No ticks
matplotlib.ticker.
LinearLocator
(numticks=None, presets=None)[source]¶Bases: matplotlib.ticker.Locator
Determine the tick locations
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 so that interactive navigation will be nice
Use presets to set locs based on lom. A dict mapping vmin, vmax>locs
matplotlib.ticker.
LogLocator
(base=10.0, subs=(1.0, ), numdecs=4, numticks=None)[source]¶Bases: matplotlib.ticker.Locator
Determine the tick locations for log axes
Place ticks on the locations : subs[j] * base**i
Parameters: 


set_params
(base=None, subs=None, numdecs=None, numticks=None)[source]¶Set parameters within this locator.
matplotlib.ticker.
AutoLocator
[source]¶Bases: matplotlib.ticker.MaxNLocator
Dynamically find major tick positions. This is actually a subclass
of MaxNLocator
, with parameters nbins = 'auto'
and steps = [1, 2, 2.5, 5, 10].
To know the values of the nonpublic parameters, please have a
look to the defaults of MaxNLocator
.
matplotlib.ticker.
MultipleLocator
(base=1.0)[source]¶Bases: matplotlib.ticker.Locator
Set a tick on each integer multiple of a base within the view interval.
matplotlib.ticker.
MaxNLocator
(*args, **kwargs)[source]¶Bases: matplotlib.ticker.Locator
Select no more than N intervals at nice locations.
Keyword args:
'auto'
, the number of bins will be
automatically determined based on the length of the axis.min_n_ticks
integers are found within the
view limits.rcParams["axes.autolimit_mode"]
is
'round_numbers'
. If prune=='lower'
, the smallest tick will
be removed. If prune == 'upper'
, the largest tick will be
removed. If prune == 'both'
, the largest and smallest ticks
will be removed. If prune == None
, no ticks will be removed.nbins
and integer
constraints if necessary to
obtain this minimum number of ticks.default_params
= {'integer': False, 'min_n_ticks': 2, 'nbins': 10, 'prune': None, 'steps': None, 'symmetric': False}¶matplotlib.ticker.
AutoMinorLocator
(n=None)[source]¶Bases: matplotlib.ticker.Locator
Dynamically find minor tick positions based on the positions of major ticks. The scale must be linear with major ticks evenly spaced.
n is 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 omitted or None, it will be set to 5 or 4.
matplotlib.ticker.
SymmetricalLogLocator
(transform=None, subs=None, linthresh=None, base=None)[source]¶Bases: matplotlib.ticker.Locator
Determine the tick locations for symmetric log axes
place ticks on the location= base**i*subs[j]
matplotlib.ticker.
LogitLocator
(minor=False)[source]¶Bases: matplotlib.ticker.Locator
Determine the tick locations for logit axes
place ticks on the logit locations