2016-09-29 85 views
0

我想在軸上最後一個tick位置之前和之後留出一些空間。例如,我只使用axis.set_xlim(),但這會干擾我的(自定義)定位器並重新生成刻度線。我發現並覆蓋了定位器類的view_limits()方法,但它們似乎不會自動調用,並且在手動調用時不會對結果圖產生任何影響。我搜索了文檔和源代碼,但沒有提出解決方案。我錯過了什麼嗎?如何在Matplotlib中設置軸的view_limits /範圍

對於更大的圖片,我想要一個定位器,它在滴答前後給我一定的空間,並選擇與MultipleLocator相似的「基」倍數的滴答點,但如果滴答數超過一個指定的值。如果有另一種方法來實現這一點,而不需要繼承一個定位器,那我都是耳朵:)。

這裏是與覆蓋view_limits - 方法的子類的定位我的示例代碼:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.ticker import MaxNLocator 

class MyLocator(MaxNLocator): 
    def __init__(self, *args, **kwargs): 
     super().__init__(*args, **kwargs) 

    def view_limits(self, dmin, dmax): 
     bins = self.bin_boundaries(dmin, dmax) 
     step = bins[1] - bins[0] 
     result = np.array([bins[0] - step, bins[-1] + step]) 
     print(result) 
     return result 

a = 10.0 
b = 99.0 

t = np.arange(a, b, 0.1) 
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01) 

loc = MyLocator(9) 

fig, ax = plt.subplots() 
plt.plot(t, s) 

ax.xaxis.set_major_locator(loc) 
loc.autoscale() # results in [ 0. 110.] but doesnt change the plot 
plt.show() 

回答

0

不知道,如果我理解你的問題是什麼徹底的,但如果你只是想添加額外的空間,可以仍然使用MaxNLocator並像這樣手動添加該空間:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.ticker import MaxNLocator 

a = 10.0 
b = 99.0 

t = np.arange(a, b, 0.1) 
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01) 

loc = MaxNLocator(9) 

fig, ax = plt.subplots() 
plt.plot(t, s) 

ax.xaxis.set_major_locator(loc) 
ticks = ax.get_xticks() 
newticks = np.zeros(len(ticks)+2) 
newticks[0] = ticks[0]- (ticks[1]-ticks[0]) 
newticks[-1] = ticks[-1]+ (ticks[1]-ticks[0]) 
newticks[1:-1] = ticks 
ax.set_xticks(newticks) 

plt.show() 
+0

感謝那個技巧!我可以與此合作。我仍然想知道爲什麼整個view_limits方法不能按預期工作。 – Fookatchu