2017-04-19 9 views
2

私は、下の図のように、1つの場所に複数のティックを入れたいと思います。Python - 複数のティックを1つの場所に入れます。

enter image description here

すなわち、 1つの小さい垂直セグメントの代わりに、軸上の特定の位置の周りに2つまたは3つ以上のものを置くことを望みます。
どうすればいいですか?

+0

私は1つの小さな垂直セグメントが、2つまたは3つまたはそれ以上の意味はない@ImportanceOfBeingErnest。 – Yola

答えて

3

マイナーダニを使用して追加のダニを生成することができます。それらの場所はFixedLocatorを使用して指定できます。その後、それぞれのrcParamsを取得することによって、主要なダニの1つと一致するようにスタイルを適応させることができます。

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をサブクラス化し、データ座標の代わりにピクセル単位で目的の位置からオフセットされた位置を戻すことができます。カスタムロケータ、 MultiTicks(locs=[4,5],nticks=[2,4])の初期化、我々はいくつかの追加のダニが表示される位置指定において
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() 

(4℃及び5)及びダニのそれぞれの数(5における4で2ティック、4ティック) 。 space引数を使用して、目盛りの間隔をピクセル数で指定することもできます。

enter image description here

+0

+1、ありがとう、どういうわけかスクリーンスペースでやってもいいですか? othrewise私はスケーリングに問題があるので、? – Yola

+1

私はあなたがそれを尋ねるのを恐れていました。 :-)これは本当に簡単ではありません。私は解決策を見つけようとします。 – ImportanceOfBeingErnest

+0

スー、それは実際にうまくいきました。それはちょうど期待されるより少しコードかもしれません。 – ImportanceOfBeingErnest

関連する問題