当前位置: 首页 > 工具软件 > Locator > 使用案例 >

matplotlib常用的的刻度定位器locator总结

文建业
2023-12-01

设置主刻度的位置

在使用matplotlib绘制图时,发现默认生成的刻度的位置总是不令人满意,这时候我们可以使用ax.xaxis.set_major_locator的方法设定刻度位置。

查看一下set_major_locator函数的头部的信息

#函数头部
def set_major_locator(self, locator):
    """
    Set the locator of the major ticker.

    Parameters
    ----------
    locator : ~matplotlib.ticker.Locator
   """
#同时还有设置次刻度的函数,使用方式是一样
set_minor_locator

要注意这个必须以及只能以locator作为形参。

locator总结

#使用时需要引入ticker中的定位器类
	from matplotlib.ticker import AutoMinorLocator,MultipleLocator,FuncFormatter,LinearLocator,NullLocator,FixedLocator,IndexLocator,AutoLocator

MultipleLocator

源码中的MultipleLocator类的注释如下:

	class MultipleLocator(Locator):
	    """
	    Set a tick on each integer multiple of a base within the view interval.
	    """

    	def __init__(self, base=1.0):
        	self._edge = _Edge_integer(base, 0)
	
从这里可以看到这个需要输入一个base的参数,然后会返回一个base的整数倍的标签,如:
	ax.set_xlim(-7.1,47)
	ax.xaxis.set_major_locator(MultipleLocator(6))
	print(ax.get_xticks())


输出的结果如下:

	[-12.  -6.   0.   6.  12.  18.  24.  30.  36.  

当我们把范围改为-5,47:

	ax.set_xlim(-5,47)
	ax.xaxis.set_major_locator(MultipleLocator(6))
	print(ax.get_xticks())

输出的结果如下:

	[-6.  0.  6. 12. 18. 24. 30. 36. 42. 48.]

可见这个会生成包括xlim的,且基于base的最小标签刻度范围。

LinearLocator,线性的定位器

这个定位器,是返回基于轴显示范围的线性等分的刻度位置

类的注释以及init函数如下:

class LinearLocator(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

    """
    def __init__(self, numticks=None, presets=None):
        """
        Use presets to set locs based on lom.  A dict mapping vmin, vmax->locs
        """
        self.numticks = numticks
        if presets is None:
            self.presets = {}
        else:
            self.presets = presets

从上可以看到,它接受一个标签数量的numticks函数,以及等分范围的presets的字典参数,若不指定presets,其实也以轴的min和max作为参数。
例如:

ax.xaxis.set_major_locator(LinearLocator(6))
print(ax.get_xticks())

结果如下(返回numpy.ndarray类型数据):

[-5.   5.4 15.8 26.2 36.6 47. ]

NullLocator,不生成刻度以及刻度标签。

这个可以达到以下设定的同样效果
plt.setp(self.Figure.ax.get_xticklabels(), visible=False)
plt.setp(self.Figure.ax.get_xticklines(), visible=False)

FixedLocator,固定位置的定位器

类的注释和init函数

	class FixedLocator(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.
	    """

	    def __init__(self, locs, nbins=None):
	        self.locs = np.asarray(locs)
	        self.nbins = max(nbins, 2) if nbins is not None else None

这个定位器接收一个我们想要标注刻度的位置的列表locs作为参数,同时也可以指定从这个locs选出最多nbins+1。而且会尽量从locs中等间隔的去除刻度。例如:

	ax.xaxis.set_major_locator(FixedLocator([0,14,26,30,35]))
	print(ax.get_xticks())

输出:
	
	[ 0 14 26 30 35]

当我们指定nbins=1时,返回[ 0 30]
当我们指定nbins=2时,返回[ 0 30]
当我们指定nbins=3时,返回[ 0 26 35]
当我们指定nbins=4时,返回[ 0 26 35]
当我们指定nbins=5时,返回[ 0 14 26 30 35]

**从这里可以看到这个nbins,一般还是不用的好,不然很容易就出错了。**

IndexLocator定位器

这个跟MultipleLocator很相似

	class IndexLocator(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.
	    """
	    def __init__(self, base, offset):
	        'place ticks on the i-th data points where (i-offset)%base==0'
	        self._base = base
	        self.offset = offset

可以看到是跟跟MultipleLocator不同的他是基于数据的。然后通过base进行等倍取点,且有一个offset的参数,可以将第一个点进行偏移。例如:

#x轴数据是从0到42的,我们设定到-5到47
ax.set_xlim(-5,47)
ax.xaxis.set_major_locator(IndexLocator(6,1))
print(ax.get_xticks())

输出的为:

	[ 1.  7. 13. 19. 25. 31. 37.]

由此可知,不根据xlim而是根据x轴的真实范围

AutoLocator 自动定位器

	class AutoLocator(MaxNLocator):
	    """
	    Dynamically find major tick positions. This is actually a subclass
	    of `~matplotlib.ticker.MaxNLocator`, with parameters *nbins = 'auto'*
	    and *steps = [1, 2, 2.5, 5, 10]*.
	    """
	    def __init__(self):
	        """
	        To know the values of the non-public parameters, please have a
	        look to the defaults of `~matplotlib.ticker.MaxNLocator`.
	        """
	        if rcParams['_internal.classic_mode']:
	            nbins = 9
	            steps = [1, 2, 5, 10]
	        else:
	            nbins = 'auto'
	            steps = [1, 2, 2.5, 5, 10]
	        MaxNLocator.__init__(self, nbins=nbins, steps=steps)
		
#会自动给我们选择间隔来设定刻度,如果没有特殊的要求,用这个很方便

AutoMinorLocator,次要刻度定位器,这个是针对次要刻度线的,

	class AutoMinorLocator(Locator):
	    """
	    Dynamically find minor tick positions based on the positions of
	    major ticks. The scale must be linear with major ticks evenly spaced.
	    """
	    def __init__(self, n=None):
	        """
	        *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.
	        """
	        self.ndivs = n

自动设定次要刻度线,但是可以指定n,进行主刻度处的n等分。
 类似资料: