Skip to main content
 首页 » 编程设计

python之Matplotlib 日期索引格式

2025年05月04日9kevingrace

我正在使用 matplotlib 绘制一些财务数据。但是,在其默认配置中,matplotlib 会插入间隙来代替缺失数据。文档建议使用 date index formatter解决这个问题。

不过,在页面提供的例子中可以看出:

  • 格式已从“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() 

请您参考如下方法:

好吧,我会回答简单的部分:要获取 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 

附言。 r.date 中的最后一个日期是 Oct 14 2008,所以我认为为它添加一个刻度线并不是一件坏事。你确定你不想要它吗?