2013-08-27 29 views
2

我想在軸上有輕微刻度但僅顯示主要刻度標籤。例如,次要標記[19,20,21,... 40,41]和主要標記標記[20,25,30,35,40]。我該怎麼做?下面的代碼沒有完成這項工作。我知道可以使用MultipleLocator,FormatStrFormatter,如this example。但是,我的軸上的值有點「奇怪」,起始值是19(不是20),最終值是41,這在使用MultipleLocator時很困難。僅顯示主要刻度標籤的小勾號

import numpy as np 
from matplotlib import pylab as plt 

fig = plt.figure() 
ax = fig.add_subplot(111) 
x = np.linspace(19.,41,23) 
y = x**2 
ax.plot(x,y) 
ax.set_xticks(x) 
ax.set_xticklabels(x, minor=False) 
plt.show() 

它給了我下面的情節: enter image description here

ax.set_xticklabels([20, 25, 30, 35, 40], minor=False) 再給我一個情節: enter image description here 我怎樣才能改變我的代碼來獲得我所需要的。非常感謝你的幫助!

+1

使用'FixedLocator'。 'set_xticks'和'set_xticklabels'是危險的,應該只使用很少。 – tacaswell

回答

13

我不明白爲什麼在你的例子中很難使用MultipleLocator

通過在代碼中添加這些行

from matplotlib.ticker import MultipleLocator, FormatStrFormatter 

majorLocator = MultipleLocator(5) 
majorFormatter = FormatStrFormatter('%d') 
minorLocator = MultipleLocator(1) 

ax.xaxis.set_major_locator(majorLocator) 
ax.xaxis.set_major_formatter(majorFormatter) 
ax.xaxis.set_minor_locator(minorLocator) 

你會得到這個形象,我明白這是你想要什麼(是不是?): enter image description here


如果您不希望標記顯示在您的數據範圍之下,請使用以下代碼手動定義標記:FixedLocator

from matplotlib.ticker import FixedLocator 

majorLocator = FixedLocator(np.linspace(20,40,5)) 
minorLocator = FixedLocator(np.linspace(19,41,23)) 

你會得到這個圖像: enter image description here

+0

是的,第二種解決方案正是我想要的。非常感謝! –

+0

真棒的答案,以及對定位器的很好的介紹。對於任何遇到這種情況的人來說,另一個注意事項是:使用'ax.set_xticks'或'ax.set_yticks'將主標記定位符更改爲'FixedLocator',這可能是更簡單的方法。 **但是**,我猜是因爲它不常見,沒有'ax.set_xminorticks'或'ax.set_yminorticks'手動選擇小勾號,所以必須使用'FixedLocator'來設置,就像這篇文章一樣。 –

相關問題