Skip to main content
 首页 » 编程设计

python之烛台的日期索引格式化程序

2024年11月01日7落叶无声

我想在使用 matplotlib 绘制股票数据时消除周末之间的“差距”。我能够做到这一点,结果如下图所示:

现在,当我尝试在 x 轴上运行索引格式化程序时,我得到的只是一张空白 Canvas 。谁能弄清楚我在这里做错了什么?如果我注释掉 FuncFormatter 行,一切都会恢复正常。

#Build parameters for candlestick graph. Adjust dates so that they are graphed equi-distant on chart 
x = 0 
y = len(date) 
ind = np.arange(y) 
 
candleAr = [] 
while x < y: 
    appendLine = ind[x], openp[x], closep[x], highp[x], lowp[x], volume[x] 
    candleAr.append(appendLine) 
    x+=1 
 
def format_date(x, pos=None): 
    thisind = np.clip(int(x+0.5), 0, y-1) 
    return candleAr.date[thisind].strftime('%Y-%m-%d') 
 
#Define plot area and candlestick chart 
fig = plt.figure(facecolor='w') 
ax1 = plt.subplot2grid((1,1), (0,0), axisbg='w') 
candlestick(ax1, candleAr, width=0.8, colorup='#9eff15', colordown='#ff1717') 
ax1.xaxis.set_major_formatter(mticker.FuncFormatter(format_date)) 
fig.autofmt_xdate() 
plt.show() 

请您参考如下方法:

对于任何感兴趣的人,这里是我如何编写 format_date 函数来让它工作:

def format_date(x, pos=None): 
        newdate = mdates.num2date(date[int(x)]) 
 
        if newdate.strftime('%m') == '02': 
            return newdate.strftime('%b\n%Y') 
        else: return newdate.strftime('%b')