2017-04-19 63 views
2

我想在一個地方有幾個刻度,如下圖所示。Python - 將幾個刻度放在一個地方

enter image description here

即而不是一個小的垂直段,我希望在軸上的特定位置附近有兩個或三個或更多的垂直段。
我怎樣才能做到這一點?

+0

@ImportanceOfBeingErnest我的意思是不是一個小的垂直段,但兩個或三個或更多。 – Yola

回答

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)和扁蝨的相應數量(2個蜱在4,4蜱在5) 。我們還可以使用參數space來指定這些刻度應該相互隔開的像素數。

enter image description here

+0

+1,謝謝,我能以某種方式在屏幕空間中做到這一點嗎?因爲酗酒我會有縮放問題嗎? – Yola

+1

我擔心你會問這個問題。 :-)這真的不容易。我會盡力找到一個解決方案。 – ImportanceOfBeingErnest

+0

很好,那確實工作得很好。它可能只比預期的多一點。 – ImportanceOfBeingErnest

相關問題