我正在使用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()
請給出一個明確的例子。代碼的和平,它打印的內容以及你想要打印的內容。 – erikbwork 2012-08-06 20:36:21
@ erikb85:我附上了文檔中使用的具體示例。它演示了tick格式的差異。 – 2012-08-06 20:42:24
@ erikb85:上面的代碼是可運行的。如果你沒有csv,matplotlib會爲你下載。 – unutbu 2012-08-06 20:49:51