2012-03-06 24 views
2

我有時間序列圖(1年以上),其中x軸的月份爲1月,2月,3月等形式,但我想只有本月的第一個字母(J,F,M等)。我設置使用刻度線使用matplotlib在x軸上設置日期爲第一個字母

ax.xaxis.set_major_locator(MonthLocator()) 
ax.xaxis.set_minor_locator(MonthLocator()) 

ax.xaxis.set_major_formatter(matplotlib.ticker.NullFormatter()) 
ax.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter('%b')) 

任何幫助,將不勝感激。

回答

2

基於官方示例here的以下代碼適用於我。

這使用基於函數的索引格式化程序來僅返回所請求的月份的第一個字母。

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.mlab as mlab 
import matplotlib.cbook as cbook 
import matplotlib.ticker as ticker 
datafile = cbook.get_sample_data('aapl.csv', asfileobj=False) 
print 'loading', datafile 
r = mlab.csv2rec(datafile) 

r.sort() 
r = r[-365:] # get the last year 

# next we'll write a custom formatter 
N = len(r) 
ind = np.arange(N) # the evenly spaced plot indices 
def format_date(x, pos=None): 
    thisind = np.clip(int(x+0.5), 0, N-1) 
    return r.date[thisind].strftime('%b')[0] 


fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.plot(ind, r.adj_close, 'o-') 
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) 
fig.autofmt_xdate() 

plt.show() 
+0

謝謝你的回覆。我會試試看,並回復你! – Darren 2012-03-07 14:29:17

3

我試圖使通過@ Appleman1234工作建議的解決方案,但因爲我自己,想創建一個解決方案,我可以保存在其他程序中的外部配置腳本和進口,我發現它不方便的格式化程序必須在格式程序功能本身之外定義變量。

我沒有解決這個問題,但我只是想在這裏分享我稍微短一點的解決方案,這樣你和其他人都可以拿走或者離開它。

事實證明,首先獲取標籤有點棘手,因爲您需要在設置刻度標籤之前繪製座標軸。否則,當您使用Text.get_text()時,您只會獲得空字符串。

您可能想要擺脫特定於我的情況的agrument minor=True

# ... 

# Manipulate tick labels 
plt.draw() 
ax.set_xticklabels(
    [t.get_text()[0] for t in ax.get_xticklabels(minor=True)], minor=True 
) 

我希望它能幫助:)

相關問題