Python - 在一个地方放几个刻度

时间:2017-04-19 13:09:42

标签: python matplotlib plot

我想在一个地方有几个刻度,如下图所示。

enter image description here

即。而不是一个小的垂直段我希望在轴上的特定位置周围有两个或三个或更多 我怎么能做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以使用次要刻度来产生额外的刻度。可以使用FixedLocator指定其位置。然后,您可以通过获取相应的rcParams来调整其样式以匹配其中一个主要刻度。

import matplotlib.pyplot as plt
import matplotlib.ticker

plt.plot([0,5],[1,1])
locs= [3.95,4.05] + [4.9,4.95,5.05,5.1]

plt.gca().xaxis.set_minor_locator(matplotlib.ticker.FixedLocator( locs ))
plt.gca().tick_params('x', length=plt.rcParams["xtick.major.size"], 
                           width=plt.rcParams["xtick.major.width"], which='minor')

plt.show()

enter image description here

<小时/> 上述问题是它与尺度有关,即对于不同的尺度,例如从4.8到5.2,蜱将远远超过预期 为了克服这个问题,我们可以对FixedLocator进行子类化,并让它返回位置,这些位置偏离所需位置,以像素为单位而不是数据坐标。

import matplotlib.pyplot as plt
import matplotlib.ticker
import matplotlib.transforms
import numpy as np

class MultiTicks(matplotlib.ticker.FixedLocator):
    def __init__(self, locs, nticks, space=3, ax=None):
        """
        @locs: list of locations where multiple ticks should be shown
        @nticks: list of number of ticks per location specified in locs
        @space: space between ticks in pixels
        """
        if not ax:
            self.ax = plt.gca()
        else:
            self.ax = ax
        self.locs = np.asarray(locs)
        self.nticks = np.asarray(nticks).astype(int)
        self.nbins = None
        self.space = space

    def tick_values(self, vmin, vmax):
        t = self.ax.transData.transform
        it = self.ax.transData.inverted().transform
        pos = []
        for i,l in enumerate(self.locs):
            x = t((l,0))[0]
            p = np.arange(0,self.nticks[i])//2+1
            for k,j in enumerate(p):
                f = (k%2)+((k+1)%2)*(-1)
                pos.append( it(( x + f*j*self.space, 0))[0] )
        return np.array(pos)


# test it:
plt.plot([0,5],[1,1])
plt.gca().xaxis.set_minor_locator(MultiTicks(locs=[4,5],nticks=[2,4]))
plt.gca().tick_params('x', length=plt.rcParams["xtick.major.size"], 
                           width=plt.rcParams["xtick.major.width"], which='minor')

plt.show()

在自定义定位器MultiTicks(locs=[4,5],nticks=[2,4])的初始化中,我们指定应出现一些额外刻度的位置(在4和5处)以及相应的刻度数(4个刻度,4刻度,4刻度) 。我们还可以使用space参数指定这些刻度应彼此间隔的像素数。

enter image description here

相关问题