2012-08-06 96 views
2

我正在使用matplotlib繪製一些財務數據。但是,在其默認配置中,matplotlib會插入空缺來代替缺失的數據。文檔建議使用date index formatter來解決此問題。Matplotlib日期索引格式

然而,可以在所提供的頁面上的實施例可以看出:

  • 格式化已經從「2008年9月3日」 =>「2008-09-03」
  • 圖表不再端改變在最後的樣本上,而是填充到「2008-10-14」。

我該如何保留這種默認行爲,同時還能避免數據中的空白?

編輯

示例代碼,從文檔,頂部所需的蜱。

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[-30:] # get the last 30 days 


# first we'll do it the default way, with gaps on weekends 
fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.plot(r.date, r.adj_close, 'o-') 
fig.autofmt_xdate() 

# 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('%Y-%m-%d') 

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

請給出一個明確的例子。代碼的和平,它打印的內容以及你想要打印的內容。 – erikbwork 2012-08-06 20:36:21

+0

@ erikb85:我附上了文檔中使用的具體示例。它演示了tick格式的差異。 – 2012-08-06 20:42:24

+0

@ erikb85:上面的代碼是可運行的。如果你沒有csv,matplotlib會爲你下載。 – unutbu 2012-08-06 20:49:51

回答

1

好吧,我會回答比較容易的部分:要獲得Sept 03 2008代替2008-09-03使用strftime('%b %d %Y')

def format_date(x, pos=None): 
    thisind = np.clip(int(x+0.5), 0, N-1) 
    result = r.date[thisind].strftime('%b %d %Y') 
    return result 

PS。 r.date中的最後一個日期是Oct 14 2008,所以我認爲爲它包括一個刻度標記並不是一件壞事。你確定你不想要嗎?

+0

這比這更復雜一點,就好像數據超過了一個更大的範圍(比如說幾年),Matplotlib可能選擇幾年(例如2007年,2008年,2009年)作爲主要的刻度線。顯然幕後有一些魔法。 – 2012-08-06 21:14:05