Matplotlib日期索引格式

问题描述:

我正在使用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

好吧,我会回答比较容易的部分:要获得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