Movatterモバイル変換


[0]ホーム

URL:


You are reading an old version of the documentation (v2.0.0). For the latest version seehttps://matplotlib.org/stable/api/ticker_api.html
matplotlib

Navigation


Travis-CI:

Table Of Contents

Related Topics

This Page

Quick search

ticker

matplotlib.ticker

Tick locating and formatting

This module contains classes to support completely configurable ticklocating and formatting. Although the locators know nothing about majoror minor ticks, they are used by the Axis class to support major andminor tick locating and formatting. Generic tick locators andformatters are provided, as well as domain specific custom ones.

Default Formatter

The default formatter identifies when the x-data beingplotted is a small range on top of a large off set. Toreduce the chances that the ticklabels overlap the ticksare labeled as deltas from a fixed offset. For example:

ax.plot(np.arange(2000,2010),range(10))

will have tick of 0-9 with an offset of +2e3. If thisis not desired turn off the use of the offset on the defaultformatter:

ax.get_xaxis().get_major_formatter().set_useOffset(False)

set the rcParamaxes.formatter.useoffset=False to turn it offglobally, or set a different formatter.

Tick locating

The Locator class is the base class for all tick locators. The locatorshandle autoscaling of the view limits based on the data limits, and thechoosing of tick locations. A useful semi-automatic tick locator isMultipleLocator. You initialize this with a base, e.g., 10, and itpicks axis limits and ticks that are multiples of your base.

The Locator subclasses defined here are

NullLocator
No ticks
FixedLocator
Tick locations are fixed
IndexLocator
locator for index plots (e.g., where x = range(len(y)))
LinearLocator
evenly spaced ticks from min to max
LogLocator
logarithmically ticks from min to max
SymmetricalLogLocator
locator for use with with the symlog norm, works like theLogLocator for the part outside of the threshold and add 0 ifinside the limits
MultipleLocator
ticks and range are a multiple of base;
either integer or float
OldAutoLocator
choose a MultipleLocator and dyamically reassign it forintelligent ticking during navigation
MaxNLocator
finds up to a max number of ticks at nice locations
AutoLocator
MaxNLocator with simple defaults. This is the defaulttick locator for most plotting.
AutoMinorLocator
locator for minor ticks when the axis is linear and themajor ticks are uniformly spaced. It subdivides the majortick interval into a specified number of minor intervals,defaulting to 4 or 5 depending on the major interval.
LogitLocator
Locator for logit scaling.

There are a number of locators specialized for date locations - seethe dates module

You can define your own locator by deriving from Locator. You mustoverride the __call__ method, which returns a sequence of locations,and you will probably want to override the autoscale method to set theview limits from the data limits.

If you want to override the default locator, use one of the above or acustom locator and pass it to the x or y axis instance. The relevantmethods are:

ax.xaxis.set_major_locator(xmajorLocator)ax.xaxis.set_minor_locator(xminorLocator)ax.yaxis.set_major_locator(ymajorLocator)ax.yaxis.set_minor_locator(yminorLocator)

The default minor locator is the NullLocator, e.g., no minor ticks on bydefault.

Tick formatting

Tick formatting is controlled by classes derived from Formatter. Theformatter operates on a single tick value and returns a string to theaxis.

NullFormatter
No labels on the ticks
IndexFormatter
Set the strings from a list of labels
FixedFormatter
Set the strings manually for the labels
FuncFormatter
User defined function sets the labels
StrMethodFormatter
Use stringformat 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 usingexponent=log_base(value).
LogFormatterMathtext
Format values for log axis usingexponent=log_base(value)using Math text.
LogFormatterSciNotation
Format values for log axis using scientific notation.
LogitFormatter
Probability formatter.

You can derive your own formatter from the Formatter base class bysimply overriding the__call__ method. The formatter class hasaccess to the axis view and data limits.

To control the major and minor tick label formats, use one of thefollowing methods:

ax.xaxis.set_major_formatter(xmajorFormatter)ax.xaxis.set_minor_formatter(xminorFormatter)ax.yaxis.set_major_formatter(ymajorFormatter)ax.yaxis.set_minor_formatter(yminorFormatter)

Seepylab_examples example code: major_minor_demo1.py for an example of settingmajor and minor ticks. See thematplotlib.dates module formore information and examples of using date locators and formatters.

classmatplotlib.ticker.TickHelper

Bases:object

axis = None
create_dummy_axis(**kwargs)
set_axis(axis)
set_bounds(vmin,vmax)
set_data_interval(vmin,vmax)
set_view_interval(vmin,vmax)
classmatplotlib.ticker.Formatter

Bases:matplotlib.ticker.TickHelper

Create a string based on a tick value and location.

fix_minus(s)

Some classes may want to replace a hyphen for minus with theproper unicode symbol (U+2212) for typographical correctness.The default is to not replace it.

Note, if you use this method, e.g., informat_data() orcall, you probably don’t want to use it forformat_data_short() since the toolbar uses this forinteractive coord reporting and I doubt we can expect GUIsacross platforms will handle the unicode correctly. So fornow the classes that overridefix_minus() should have anexplicitformat_data_short() method

format_data(value)

Returns the full string representation of the value with theposition unspecified.

format_data_short(value)

Return a short string version of the tick value.

Defaults to the position-independent long value.

get_offset()
locs = []
set_locs(locs)
classmatplotlib.ticker.FixedFormatter(seq)

Bases:matplotlib.ticker.Formatter

Return fixed strings for tick labels based only on position, notvalue.

Set the sequence of strings that will be used for labels.

get_offset()
set_offset_string(ofs)
classmatplotlib.ticker.NullFormatter

Bases:matplotlib.ticker.Formatter

Always return the empty string.

classmatplotlib.ticker.FuncFormatter(func)

Bases:matplotlib.ticker.Formatter

Use a user-defined function for formatting.

The function should take in two inputs (a tick valuex and apositionpos), and return a string containing the correspondingtick label.

classmatplotlib.ticker.FormatStrFormatter(fmt)

Bases:matplotlib.ticker.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.

classmatplotlib.ticker.StrMethodFormatter(fmt)

Bases:matplotlib.ticker.Formatter

Use a new-style format string (as used bystr.format())to format the tick.

The field used for the value must be labeledx and the field usedfor the position must be labeledpos.

classmatplotlib.ticker.ScalarFormatter(useOffset=None,useMathText=None,useLocale=None)

Bases:matplotlib.ticker.Formatter

Format tick values as a number.

Tick value is interpreted as a plain old number. IfuseOffset==True and the data range is much smaller than the dataaverage, then an offset will be determined such that the tick labelsare meaningful. Scientific notation is used fordata<10^-n ordata>=10^m, wheren andm are the power limits setusingset_powerlimits((n,m)). The defaults for these arecontrolled by theaxes.formatter.limits rc parameter.

fix_minus(s)

Replace hyphens with a unicode minus.

format_data(value)

Return a formatted string representation of a number.

format_data_short(value)

Return a short formatted string representation of a number.

get_offset()

Return scientific notation, plus offset.

get_useLocale()
get_useOffset()
pprint_val(x)
set_locs(locs)

Set the locations of the ticks.

set_powerlimits(lims)

Sets size thresholds for scientific notation.

lims is a two-element sequence containing the powers of 10that determine the switchover threshold. Numbers below10**lims[0] and above10**lims[1] will be displayed inscientific notation.

For example,formatter.set_powerlimits((-3,4)) sets thepre-2007 default in which scientific notation is used fornumbers less than 1e-3 or greater than 1e4.

See also

Methodset_scientific()

set_scientific(b)

Turn scientific notation on or off.

See also

Methodset_powerlimits()

set_useLocale(val)
set_useOffset(val)
useLocale
useOffset
classmatplotlib.ticker.LogFormatter(base=10.0,labelOnlyBase=False,minor_thresholds=None,linthresh=None)

Bases:matplotlib.ticker.Formatter

Base class for formatting ticks on a log or symlog scale.

It may be instantiated directly, or subclassed.

Parameters:

base : float, optional, default: 10.

Base of the logarithm used in all calculations.

labelOnlyBase : bool, optional, default: False

If True, label ticks only at integer powers of base.This is normally True for major ticks and False forminor ticks.

minor_thresholds : (subset, all), optional, default: (1, 0.4)

If labelOnlyBase is False, these two numbers controlthe labeling of ticks that are not at integer powers ofbase; normally these are the minor ticks. The controllingparameter is the log of the axis data range. In the typicalcase where base is 10 it is the number of decades spannedby the axis, so we can call it ‘numdec’. Ifnumdec<=all,all minor ticks will be labeled. Ifall<numdec<=subset,then only a subset of minor ticks will be labeled, so as toavoid crowding. Ifnumdec>subset then no minor ticks willbe labeled.

linthresh : None or float, optional, default: None

If a symmetric log scale is in use, itslinthreshparameter must be supplied here.

Notes

Theset_locs method must be called to enable the subsettinglogic controlled by theminor_thresholds parameter.

In some cases such as the colorbar, there is no distinction betweenmajor and minor ticks; the tick locations might be set manually,or by a locator that puts ticks at integer powers of base andat intermediate locations. For this situation, disable theminor_thresholds logic by usingminor_thresholds=(np.inf,np.inf),so that all ticks will be labeled.

To disable labeling of minor ticks when ‘labelOnlyBase’ is False,useminor_thresholds=(0,0). This is the default for the“classic” style.

Examples

To label a subset of minor ticks when the view limits span upto 2 decades, and all of the ticks when zoomed in to 0.5 decadesor less, useminor_thresholds=(2,0.5).

To label all minor ticks when the view limits span up to 1.5decades, useminor_thresholds=(1.5,1.5).

base(base)

change thebase for labeling.

Warning

Should always match the base used forLogLocator

format_data(value)
format_data_short(value)

Return a short formatted string representation of a number.

label_minor(labelOnlyBase)

Switch minor tick labeling on or off.

Parameters:

labelOnlyBase : bool

If True, label ticks only at integer powers of base.

pprint_val(x,d)
set_locs(locs=None)

Use axis view limits to control which ticks are labeled.

Thelocs parameter is ignored in the present algorithm.

classmatplotlib.ticker.LogFormatterExponent(base=10.0,labelOnlyBase=False,minor_thresholds=None,linthresh=None)

Bases:matplotlib.ticker.LogFormatter

Format values for log axis usingexponent=log_base(value).

classmatplotlib.ticker.LogFormatterMathtext(base=10.0,labelOnlyBase=False,minor_thresholds=None,linthresh=None)

Bases:matplotlib.ticker.LogFormatter

Format values for log axis usingexponent=log_base(value).

classmatplotlib.ticker.Locator

Bases:matplotlib.ticker.TickHelper

Determine the tick locations;

Note, you should not use the same locator between differentAxis because the locator stores references tothe Axis data and view limits

MAXTICKS = 1000
autoscale()

autoscale the view limits

pan(numsteps)

Pan numticks (can be positive or negative)

raise_if_exceeds(locs)

raise a RuntimeError if Locator attempts to create more thanMAXTICKS locs

refresh()

refresh internal information based on current lim

set_params(**kwargs)

Do nothing, and rase a warning. Any locator class not supporting theset_params() function will call this.

tick_values(vmin,vmax)

Return the values of the located ticks givenvmin andvmax.

Note

To get tick locations with the vmin and vmax values definedautomatically for the associatedaxis simply callthe Locator instance:

>>>print((type(loc)))<type 'Locator'>>>>print((loc()))[1, 2, 3, 4]
view_limits(vmin,vmax)

select a scale for the range from vmin to vmax

Normally this method is overridden by subclasses tochange locator behaviour.

zoom(direction)

Zoom in/out on axis; if direction is >0 zoom in, else zoom out

classmatplotlib.ticker.IndexLocator(base,offset)

Bases:matplotlib.ticker.Locator

Place a tick on every multiple of some base number of pointsplotted, e.g., on every 5th point. It is assumed that you are doingindex plotting; i.e., the axis is 0, len(data). This is mainlyuseful for x ticks.

place ticks on the i-th data points where (i-offset)%base==0

set_params(base=None,offset=None)

Set parameters within this locator

tick_values(vmin,vmax)
classmatplotlib.ticker.FixedLocator(locs,nbins=None)

Bases:matplotlib.ticker.Locator

Tick locations are fixed. If nbins is not None,the array of possible positions will be subsampled tokeep the number of ticks <= nbins +1.The subsampling will be done so as to include the smallestabsolute value; for example, if zero is included in thearray of possibilities, then it is guaranteed to be one ofthe chosen ticks.

set_params(nbins=None)

Set parameters within this locator.

tick_values(vmin,vmax)

”Return the locations of the ticks.

Note

Because the values are fixed, vmin and vmax are not used in thismethod.

classmatplotlib.ticker.NullLocator

Bases:matplotlib.ticker.Locator

No ticks

tick_values(vmin,vmax)

”Return the locations of the ticks.

Note

Because the values are Null, vmin and vmax are not used in thismethod.

classmatplotlib.ticker.LinearLocator(numticks=None,presets=None)

Bases:matplotlib.ticker.Locator

Determine the tick locations

The first time this function is called it will try to set thenumber of ticks to make a nice tick partitioning. Thereafter thenumber of ticks will be fixed so that interactive navigation willbe nice

Use presets to set locs based on lom. A dict mapping vmin, vmax->locs

set_params(numticks=None,presets=None)

Set parameters within this locator.

tick_values(vmin,vmax)
view_limits(vmin,vmax)

Try to choose the view limits intelligently

classmatplotlib.ticker.LogLocator(base=10.0,subs=(1.0,),numdecs=4,numticks=None)

Bases:matplotlib.ticker.Locator

Determine the tick locations for log axes

Place ticks on the locations : subs[j] * base**i

Parameters:

subs : None, string, or sequence of float, optional, default (1.0,)

Gives the multiples of integer powers of the base at whichto place ticks. The default places ticks only atinteger powers of the base.The permitted string values are'auto' and'all',both of which use an algorithm based on the axis viewlimits to determine whether and how to put ticks betweeninteger powers of the base. With'auto', ticks areplaced only between integer powers; with'all', theinteger powers are included. A value of None isequivalent to'auto'.

base(base)

set the base of the log scaling (major tick every base**i, i integer)

nonsingular(vmin,vmax)
set_params(base=None,subs=None,numdecs=None,numticks=None)

Set parameters within this locator.

subs(subs)

set the minor ticks for the log scaling every base**i*subs[j]

tick_values(vmin,vmax)
view_limits(vmin,vmax)

Try to choose the view limits intelligently

classmatplotlib.ticker.AutoLocator

Bases:matplotlib.ticker.MaxNLocator

classmatplotlib.ticker.MultipleLocator(base=1.0)

Bases:matplotlib.ticker.Locator

Set a tick on every integer that is multiple of base in theview interval

set_params(base)

Set parameters within this locator.

tick_values(vmin,vmax)
view_limits(dmin,dmax)

Set the view limits to the nearest multiples of base thatcontain the data

classmatplotlib.ticker.MaxNLocator(*args,**kwargs)

Bases:matplotlib.ticker.Locator

Select no more than N intervals at nice locations.

Keyword args:

nbins
Maximum number of intervals; one less than max number ofticks. If the string'auto', the number of bins will beautomatically determined based on the length of the axis.
steps
Sequence of nice numbers starting with 1 and ending with 10;e.g., [1, 2, 4, 5, 10]
integer
If True, ticks will take only integer values, providedat leastmin_n_ticks integers are found within theview limits.
symmetric
If True, autoscaling will result in a range symmetricabout zero.
prune
[‘lower’ | ‘upper’ | ‘both’ | None]Remove edge ticks – useful for stacked or ganged plotswhere the upper tick of one axes overlaps with the lowertick of the axes above it, primarily whenrcParams['axes.autolimit_mode'] is'round_numbers'.Ifprune=='lower', the smallest tick willbe removed. Ifprune=='upper', the largest tick will beremoved. Ifprune=='both', the largest and smallest tickswill be removed. Ifprune==None, no ticks will be removed.
min_n_ticks
Relaxnbins andinteger constraints if necessary toobtain this minimum number of ticks.
bin_boundaries(vmin,vmax)

Deprecated since version 2.0:The bin_boundaries function was deprecated in version 2.0.

default_params = {'nbins': 10, 'steps': None, 'integer': False, 'symmetric': False, 'prune': None, 'min_n_ticks': 2}
set_params(**kwargs)

Set parameters within this locator.

tick_values(vmin,vmax)
view_limits(dmin,dmax)
classmatplotlib.ticker.AutoMinorLocator(n=None)

Bases:matplotlib.ticker.Locator

Dynamically find minor tick positions based on the positions ofmajor ticks. Assumes the scale is linear and major ticks areevenly spaced.

n is the number of subdivisions of the interval betweenmajor ticks; e.g., n=2 will place a single minor tick midwaybetween major ticks.

Ifn is omitted or None, it will be set to 5 or 4.

tick_values(vmin,vmax)
classmatplotlib.ticker.SymmetricalLogLocator(transform=None,subs=None,linthresh=None,base=None)

Bases:matplotlib.ticker.Locator

Determine the tick locations for symmetric log axes

place ticks on the location= base**i*subs[j]

set_params(subs=None,numticks=None)

Set parameters within this locator.

tick_values(vmin,vmax)
view_limits(vmin,vmax)

Try to choose the view limits intelligently

© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2016 The Matplotlib development team. Last updated on Feb 20, 2017. Created usingSphinx 1.5.2.

[8]ページ先頭

©2009-2025 Movatter.jp